diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 74940a5a754..00000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,26 +0,0 @@ -version: 2 -jobs: - build: - branches: - only: - - master - - develop - - addinCircleCI - - docker: - - image: circleci/openjdk:8-jdk-browsers - working_directory: ~/java-tron - steps: - - checkout - - run: - name: multi_os_result - command: echo "curl http://60.205.215.34/multi_os_result" -# -# - run: -# name: Daily Build Report -# command: curl http://47.95.206.44:50080/Daily_Build_Task_Report -# -# - run: -# name: Download Links -# command: sh DownloadLinks.sh - diff --git a/.gitignore b/.gitignore index 9b19aa5de68..6309bbd79a5 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,5 @@ Wallet # vm_trace /vm_trace/ + +/framework/propPath diff --git a/DownloadLinks.sh b/DownloadLinks.sh deleted file mode 100644 index babc5a266f6..00000000000 --- a/DownloadLinks.sh +++ /dev/null @@ -1,21 +0,0 @@ -PassFlag=`curl -s http://47.95.206.44:50080/Daily_Build_Task_Report | grep "Failed: 0" | wc -c` - -if [ $PassFlag -eq 0 ]; then - echo "Daily Build Stest Fail" - echo "To view Daily Replay and Stress Test logs please visit website below on browsers" - echo "--- http://47.95.206.44:50080/latestReplayLog" - echo "--- http://47.95.206.44:50080/latestStressLog" - -else - echo "Daily Build Stest Pass" - echo "Build on `date +"%Y-%m-%d"` 3:00:00 (CST), UTC +8" - echo "Please visit following website to download java-tron.jar on browsers" - echo "--- http://47.95.206.44:50080/Daily_Build/jFava-tron.jar" - echo "To view Daily Replay and Stress Test logs please visit website below on browsers" - echo "--- http://47.95.206.44:50080/latestReplayLog" - echo "--- http://47.95.206.44:50080/latestStressLog" - echo "The following compressed package is provided for user to set up Fullnode. Please use Linux OS to Download" - echo "--- curl -# -O http://47.95.206.44:50080/Daily_Build/java-tron.tar.gz" - echo "To unzip file use the command below" - echo "--- tar -xzvf java-tron.tar.gz" -fi \ No newline at end of file diff --git a/Tron protobuf protocol document.md b/Tron protobuf protocol document.md index f6fa2219ce3..852ff313797 100644 --- a/Tron protobuf protocol document.md +++ b/Tron protobuf protocol document.md @@ -627,6 +627,7 @@ Transaction and transaction-related messages. WithdrawExpireUnfreezeContract = 56; DelegateResourceContract = 57; UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; @@ -887,6 +888,7 @@ Contract and contract-related messages. WithdrawExpireUnfreezeContract = 56; DelegateResourceContract = 57; UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; diff --git a/actuator/build.gradle b/actuator/build.gradle index 3db2e55b3de..a230ef4ca7e 100644 --- a/actuator/build.gradle +++ b/actuator/build.gradle @@ -3,7 +3,7 @@ description = "actuator – a series of transactions for blockchain." // Dependency versions // --------------------------------------- -def junitVersion = "4.12" +def junitVersion = "4.13.2" def mockitoVersion = "2.1.0" def testNgVersion = "6.11" def slf4jVersion = "1.7.25" diff --git a/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java new file mode 100755 index 00000000000..527c88115ac --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java @@ -0,0 +1,201 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +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 com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol.Account.UnFreezeV2; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract; + +@Slf4j(topic = "actuator") +public class CancelAllUnfreezeV2Actuator extends AbstractActuator { + + public CancelAllUnfreezeV2Actuator() { + super(ContractType.CancelAllUnfreezeV2Contract, CancelAllUnfreezeV2Contract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + long fee = calcFee(); + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + byte[] ownerAddress; + try { + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + AccountCapsule ownerCapsule = accountStore.get(ownerAddress); + List unfrozenV2List = ownerCapsule.getUnfrozenV2List(); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + AtomicLong atomicWithdrawExpireBalance = new AtomicLong(0L); + Triple, Pair, Pair> + triple = Triple.of( + Pair.of(new AtomicLong(0L), new AtomicLong(0L)), + Pair.of(new AtomicLong(0L), new AtomicLong(0L)), + Pair.of(new AtomicLong(0L), new AtomicLong(0L))); + for (UnFreezeV2 unFreezeV2 : unfrozenV2List) { + updateAndCalculate(triple, ownerCapsule, now, atomicWithdrawExpireBalance, unFreezeV2); + } + ownerCapsule.clearUnfrozenV2(); + addTotalResourceWeight(dynamicStore, triple); + + long withdrawExpireBalance = atomicWithdrawExpireBalance.get(); + if (withdrawExpireBalance > 0) { + ownerCapsule.setBalance(ownerCapsule.getBalance() + withdrawExpireBalance); + } + + accountStore.put(ownerCapsule.createDbKey(), ownerCapsule); + ret.setWithdrawExpireAmount(withdrawExpireBalance); + Map cancelUnfreezeV2AmountMap = new HashMap<>(); + cancelUnfreezeV2AmountMap.put(BANDWIDTH.name(), triple.getLeft().getRight().get()); + cancelUnfreezeV2AmountMap.put(ENERGY.name(), triple.getMiddle().getRight().get()); + cancelUnfreezeV2AmountMap.put(TRON_POWER.name(), triple.getRight().getRight().get()); + ret.putAllCancelUnfreezeV2AmountMap(cancelUnfreezeV2AmountMap); + ret.setStatus(fee, code.SUCESS); + return true; + } + + private void addTotalResourceWeight(DynamicPropertiesStore dynamicStore, + Triple, + Pair, + Pair> triple) { + dynamicStore.addTotalNetWeight(triple.getLeft().getLeft().get()); + dynamicStore.addTotalEnergyWeight(triple.getMiddle().getLeft().get()); + dynamicStore.addTotalTronPowerWeight(triple.getRight().getLeft().get()); + } + + private void updateAndCalculate(Triple, Pair, + Pair> triple, + AccountCapsule ownerCapsule, long now, AtomicLong atomicLong, UnFreezeV2 unFreezeV2) { + if (unFreezeV2.getUnfreezeExpireTime() > now) { + updateFrozenInfoAndTotalResourceWeight(ownerCapsule, unFreezeV2, triple); + } else { + atomicLong.addAndGet(unFreezeV2.getUnfreezeAmount()); + } + } + + @Override + public boolean validate() throws ContractValidateException { + if (Objects.isNull(this.any)) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + + if (Objects.isNull(chainBaseManager)) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + + if (!this.any.is(CancelAllUnfreezeV2Contract.class)) { + throw new ContractValidateException("contract type error, expected type " + + "[CancelAllUnfreezeV2Contract], real type[" + any.getClass() + "]"); + } + + if (!dynamicStore.supportAllowCancelAllUnfreezeV2()) { + throw new ContractValidateException("Not support CancelAllUnfreezeV2 transaction," + + " need to be opened by the committee"); + } + + byte[] ownerAddress; + try { + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + if (Objects.isNull(accountCapsule)) { + throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + + List unfrozenV2List = accountCapsule.getUnfrozenV2List(); + if (unfrozenV2List.isEmpty()) { + throw new ContractValidateException("No unfreezeV2 list to cancel"); + } + + return true; + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return getCancelAllUnfreezeV2Contract().getOwnerAddress(); + } + + private CancelAllUnfreezeV2Contract getCancelAllUnfreezeV2Contract() + throws InvalidProtocolBufferException { + return any.unpack(CancelAllUnfreezeV2Contract.class); + } + + @Override + public long calcFee() { + return 0; + } + + public void updateFrozenInfoAndTotalResourceWeight( + AccountCapsule accountCapsule, UnFreezeV2 unFreezeV2, + Triple, Pair, + Pair> triple) { + switch (unFreezeV2.getType()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(unFreezeV2.getUnfreezeAmount()); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + triple.getLeft().getLeft().addAndGet(newNetWeight - oldNetWeight); + triple.getLeft().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(unFreezeV2.getUnfreezeAmount()); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + triple.getMiddle().getLeft().addAndGet(newEnergyWeight - oldEnergyWeight); + triple.getMiddle().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(unFreezeV2.getUnfreezeAmount()); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + triple.getRight().getLeft().addAndGet(newTPWeight - oldTPWeight); + triple.getRight().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + default: + break; + } + } +} 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..c54c00b5697 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,9 @@ 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.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -46,8 +49,10 @@ public boolean execute(Object result) throws ContractExeException { long fee = calcFee(); final DelegateResourceContract delegateResourceContract; AccountStore accountStore = chainBaseManager.getAccountStore(); + byte[] ownerAddress; try { - delegateResourceContract = any.unpack(DelegateResourceContract.class); + delegateResourceContract = this.any.unpack(DelegateResourceContract.class); + ownerAddress = getOwnerAddress().toByteArray(); } catch (InvalidProtocolBufferException e) { logger.debug(e.getMessage(), e); ret.setStatus(fee, code.FAILED); @@ -56,24 +61,24 @@ public boolean execute(Object result) throws ContractExeException { AccountCapsule ownerCapsule = accountStore .get(delegateResourceContract.getOwnerAddress().toByteArray()); - + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); long delegateBalance = delegateResourceContract.getBalance(); boolean lock = delegateResourceContract.getLock(); - byte[] ownerAddress = delegateResourceContract.getOwnerAddress().toByteArray(); + long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract); byte[] receiverAddress = delegateResourceContract.getReceiverAddress().toByteArray(); // delegate resource to receiver switch (delegateResourceContract.getResource()) { case BANDWIDTH: delegateResource(ownerAddress, receiverAddress, true, - delegateBalance, lock); + delegateBalance, lock, lockPeriod); ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(delegateBalance); ownerCapsule.addFrozenBalanceForBandwidthV2(-delegateBalance); break; case ENERGY: delegateResource(ownerAddress, receiverAddress, false, - delegateBalance, lock); + delegateBalance, lock, lockPeriod); ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(delegateBalance); ownerCapsule.addFrozenBalanceForEnergyV2(-delegateBalance); @@ -100,6 +105,7 @@ public boolean validate() throws ContractValidateException { } AccountStore accountStore = chainBaseManager.getAccountStore(); DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); if (!any.is(DelegateResourceContract.class)) { throw new ContractValidateException( "contract type error,expected type [DelegateResourceContract],real type[" @@ -116,13 +122,14 @@ public boolean validate() throws ContractValidateException { } final DelegateResourceContract delegateResourceContract; + byte[] ownerAddress; try { delegateResourceContract = this.any.unpack(DelegateResourceContract.class); + ownerAddress = getOwnerAddress().toByteArray(); } catch (InvalidProtocolBufferException e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); } - byte[] ownerAddress = delegateResourceContract.getOwnerAddress().toByteArray(); if (!DecodeUtil.addressValid(ownerAddress)) { throw new ContractValidateException("Invalid address"); } @@ -210,6 +217,38 @@ public boolean validate() throws ContractValidateException { + readableOwnerAddress + NOT_EXIST_STR); } + boolean lock = delegateResourceContract.getLock(); + if (lock && dynamicStore.supportMaxDelegateLockPeriod()) { + long lockPeriod = getLockPeriod(dynamicStore, delegateResourceContract); + long maxDelegateLockPeriod = dynamicStore.getMaxDelegateLockPeriod(); + if (lockPeriod < 0 || lockPeriod > maxDelegateLockPeriod) { + throw new ContractValidateException( + "The lock period of delegate resource cannot be less than 0 and cannot exceed " + + maxDelegateLockPeriod + "!"); + } + + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, true); + DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + if (delegatedResourceCapsule != null) { + switch (delegateResourceContract.getResource()) { + case BANDWIDTH: { + validRemainTime(BANDWIDTH, lockPeriod, + delegatedResourceCapsule.getExpireTimeForBandwidth(), now); + } + break; + case ENERGY: { + validRemainTime(ENERGY, lockPeriod, + delegatedResourceCapsule.getExpireTimeForEnergy(), now); + } + break; + default: + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + } + if (receiverCapsule.getType() == AccountType.Contract) { throw new ContractValidateException( "Do not allow delegate resources to contract addresses"); @@ -218,6 +257,27 @@ public boolean validate() throws ContractValidateException { return true; } + private long getLockPeriod(DynamicPropertiesStore dynamicStore, + DelegateResourceContract delegateResourceContract) { + long lockPeriod = delegateResourceContract.getLockPeriod(); + if (dynamicStore.supportMaxDelegateLockPeriod()) { + return lockPeriod == 0 ? DELEGATE_PERIOD / 3000 : lockPeriod; + } else { + return 0; + } + } + + private void validRemainTime(ResourceCode resourceCode, long lockPeriod, long expireTime, + long now) throws ContractValidateException { + long remainTime = expireTime - now; + if (lockPeriod * 3 * 1000 < 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 " + + resourceCode.name() + "!"); + } + } + @Override public ByteString getOwnerAddress() throws InvalidProtocolBufferException { return any.unpack(DelegateResourceContract.class).getOwnerAddress(); @@ -229,7 +289,7 @@ public long calcFee() { } private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boolean isBandwidth, - long balance, boolean lock) { + long balance, boolean lock, long lockPeriod) { AccountStore accountStore = chainBaseManager.getAccountStore(); DynamicPropertiesStore dynamicPropertiesStore = chainBaseManager.getDynamicPropertiesStore(); DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); @@ -241,12 +301,15 @@ private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boole delegatedResourceStore.unLockExpireResource(ownerAddress, receiverAddress, now); //modify DelegatedResourceStore - byte[] key; long expireTime = 0; if (lock) { - expireTime = now + DELEGATE_PERIOD; + if (dynamicPropertiesStore.supportMaxDelegateLockPeriod()) { + expireTime = now + lockPeriod * 3 * 1000; + } else { + expireTime = now + DELEGATE_PERIOD; + } } - key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, lock); + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, lock); DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key); if (delegatedResourceCapsule == null) { delegatedResourceCapsule = new DelegatedResourceCapsule(ByteString.copyFrom(ownerAddress), diff --git a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java index a32e81a33a4..326e2472757 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -4,6 +4,7 @@ import static java.lang.Math.min; import static org.apache.commons.lang3.ArrayUtils.getLength; import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.ByteString; import java.math.BigInteger; @@ -58,7 +59,6 @@ import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.contract.Common; import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; @@ -568,12 +568,13 @@ public long getAccountEnergyLimitWithFixRatio(AccountCapsule account, long feeLi energyProcessor.updateUsage(account); account.setLatestConsumeTimeForEnergy(now); receipt.setCallerEnergyUsage(account.getEnergyUsage()); - receipt.setCallerEnergyWindowSize(account.getWindowSize(Common.ResourceCode.ENERGY)); + receipt.setCallerEnergyWindowSize(account.getWindowSize(ENERGY)); + receipt.setCallerEnergyWindowSizeV2(account.getWindowSizeV2(ENERGY)); account.setEnergyUsage( - energyProcessor.increase(account, Common.ResourceCode.ENERGY, + energyProcessor.increase(account, ENERGY, account.getEnergyUsage(), min(leftFrozenEnergy, energyFromFeeLimit), now, now)); receipt.setCallerEnergyMergedUsage(account.getEnergyUsage()); - receipt.setCallerEnergyMergedWindowSize(account.getWindowSize(Common.ResourceCode.ENERGY)); + receipt.setCallerEnergyMergedWindowSize(account.getWindowSize(ENERGY)); rootRepository.updateAccount(account.createDbKey(), account); } return min(availableEnergy, energyFromFeeLimit); @@ -730,12 +731,13 @@ public long getTotalEnergyLimitWithFixRatio(AccountCapsule creator, AccountCapsu energyProcessor.updateUsage(creator); creator.setLatestConsumeTimeForEnergy(now); receipt.setOriginEnergyUsage(creator.getEnergyUsage()); - receipt.setOriginEnergyWindowSize(creator.getWindowSize(Common.ResourceCode.ENERGY)); + receipt.setOriginEnergyWindowSize(creator.getWindowSize(ENERGY)); + receipt.setOriginEnergyWindowSizeV2(creator.getWindowSizeV2(ENERGY)); creator.setEnergyUsage( - energyProcessor.increase(creator, Common.ResourceCode.ENERGY, + energyProcessor.increase(creator, ENERGY, creator.getEnergyUsage(), creatorEnergyLimit, now, now)); receipt.setOriginEnergyMergedUsage(creator.getEnergyUsage()); - receipt.setOriginEnergyMergedWindowSize(creator.getWindowSize(Common.ResourceCode.ENERGY)); + receipt.setOriginEnergyMergedWindowSize(creator.getWindowSize(ENERGY)); rootRepository.updateAccount(creator.createDbKey(), creator); } return Math.addExact(callerEnergyLimit, creatorEnergyLimit); 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 5597f985291..0e0cc81446c 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -681,6 +681,51 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } + case ALLOW_TVM_SHANGHAI: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_TVM_SHANGHAI]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_TVM_SHANGHAI] is only allowed to be 1"); + } + break; + } + case ALLOW_CANCEL_ALL_UNFREEZE_V2: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_CANCEL_ALL_UNFREEZE_V2]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_CANCEL_ALL_UNFREEZE_V2] is only allowed to be 1"); + } + if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) { + throw new ContractValidateException( + "[UNFREEZE_DELAY_DAYS] proposal must be approved " + + "before [ALLOW_CANCEL_ALL_UNFREEZE_V2] can be proposed"); + } + break; + } + case MAX_DELEGATE_LOCK_PERIOD: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [MAX_DELEGATE_LOCK_PERIOD]"); + } + long maxDelegateLockPeriod = dynamicPropertiesStore.getMaxDelegateLockPeriod(); + if (value <= maxDelegateLockPeriod || value > 10512000L) { + throw new ContractValidateException( + "This value[MAX_DELEGATE_LOCK_PERIOD] is only allowed to be greater than " + + maxDelegateLockPeriod + " and less than or equal to 10512000 !"); + } + if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) { + throw new ContractValidateException( + "[UNFREEZE_DELAY_DAYS] proposal must be approved " + + "before [MAX_DELEGATE_LOCK_PERIOD] can be proposed"); + } + break; + } default: break; } @@ -753,7 +798,10 @@ public enum ProposalType { // current value, value range ALLOW_DYNAMIC_ENERGY(72), // 0, 1 DYNAMIC_ENERGY_THRESHOLD(73), // 0, [0, LONG] DYNAMIC_ENERGY_INCREASE_FACTOR(74), // 0, [0, 10_000] - DYNAMIC_ENERGY_MAX_FACTOR(75); // 0, [0, 100_000] + DYNAMIC_ENERGY_MAX_FACTOR(75), // 0, [0, 100_000] + ALLOW_TVM_SHANGHAI(76), // 0, 1 + ALLOW_CANCEL_ALL_UNFREEZE_V2(77), // 0, 1 + MAX_DELEGATE_LOCK_PERIOD(78); // (86400, 10512000] private long code; 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..462a80fa600 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -278,13 +278,19 @@ public static long consumeBandWidthSize( return bytesSize; } - - public static long estimateConsumeBandWidthSize( - final AccountCapsule ownerCapsule, - ChainBaseManager chainBaseManager) { - DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() - .setLock(true) - .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + 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); diff --git a/actuator/src/main/java/org/tron/core/vm/Op.java b/actuator/src/main/java/org/tron/core/vm/Op.java index 557619f554b..f6987c12942 100644 --- a/actuator/src/main/java/org/tron/core/vm/Op.java +++ b/actuator/src/main/java/org/tron/core/vm/Op.java @@ -148,6 +148,7 @@ public class Op { /* Push Operations */ // Place item on stack + public static final int PUSH0 = 0x5f; public static final int PUSH1 = 0x60; public static final int PUSH2 = 0x61; public static final int PUSH3 = 0x62; diff --git a/actuator/src/main/java/org/tron/core/vm/OperationActions.java b/actuator/src/main/java/org/tron/core/vm/OperationActions.java index 9895b24910f..5ed6ead075f 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationActions.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationActions.java @@ -643,6 +643,11 @@ public static void jumpDestAction(Program program) { program.step(); } + public static void push0Action(Program program) { + program.stackPush(DataWord.ZERO()); + program.step(); + } + public static void pushAction(Program program) { int n = program.getCurrentOpIntValue() - Op.PUSH1 + 1; program.step(); diff --git a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java index 0df5a6b126f..e4b1e174702 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java @@ -11,6 +11,7 @@ public enum Version { TRON_V1_0, TRON_V1_1, TRON_V1_2, + TRON_V1_3, // add more // TRON_V2, // ETH @@ -22,6 +23,7 @@ public enum Version { tableMap.put(Version.TRON_V1_0, newTronV10OperationSet()); tableMap.put(Version.TRON_V1_1, newTronV11OperationSet()); tableMap.put(Version.TRON_V1_2, newTronV12OperationSet()); + tableMap.put(Version.TRON_V1_3, newTronV13OperationSet()); } public static JumpTable newTronV10OperationSet() { @@ -47,12 +49,18 @@ public static JumpTable newTronV12OperationSet() { return table; } + public static JumpTable newTronV13OperationSet() { + JumpTable table = newTronV12OperationSet(); + appendShangHaiOperations(table); + return table; + } + // Just for warming up class to avoid out_of_time public static void init() {} public static JumpTable getTable() { // always get the table which has the newest version - JumpTable table = tableMap.get(Version.TRON_V1_2); + JumpTable table = tableMap.get(Version.TRON_V1_3); // next make the corresponding changes, exclude activating opcode if (VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx()) { @@ -617,4 +625,14 @@ public static void appendDelegateOperations(JumpTable table) { OperationActions::unDelegateResourceAction, proposal)); } + + public static void appendShangHaiOperations(JumpTable table) { + BooleanSupplier proposal = VMConfig::allowTvmShanghai; + + table.set(new Operation( + Op.PUSH0, 0, 1, + EnergyCost::getBaseTierCost, + OperationActions::push0Action, + proposal)); + } } diff --git a/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java b/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java index 8c597bc50bf..463d8c8995a 100644 --- a/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java +++ b/actuator/src/main/java/org/tron/core/vm/config/ConfigLoader.java @@ -38,6 +38,7 @@ public static void load(StoreFactory storeFactory) { VMConfig.initDynamicEnergyThreshold(ds.getDynamicEnergyThreshold()); VMConfig.initDynamicEnergyIncreaseFactor(ds.getDynamicEnergyIncreaseFactor()); VMConfig.initDynamicEnergyMaxFactor(ds.getDynamicEnergyMaxFactor()); + VMConfig.initAllowTvmShangHai(ds.getAllowTvmShangHai()); } } } diff --git a/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java b/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java index 004fb5ffb8f..97202432598 100644 --- a/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java +++ b/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java @@ -47,6 +47,8 @@ public class VMConfig { private static long DYNAMIC_ENERGY_MAX_FACTOR = 0L; + private static boolean ALLOW_TVM_SHANGHAI = false; + private VMConfig() { } @@ -130,6 +132,10 @@ public static void initDynamicEnergyMaxFactor(long maxFactor) { DYNAMIC_ENERGY_MAX_FACTOR = maxFactor; } + public static void initAllowTvmShangHai(long allow) { + ALLOW_TVM_SHANGHAI = allow == 1; + } + public static boolean getEnergyLimitHardFork() { return CommonParameter.ENERGY_LIMIT_HARD_FORK; } @@ -201,4 +207,8 @@ public static long getDynamicEnergyIncreaseFactor() { public static long getDynamicEnergyMaxFactor() { return DYNAMIC_ENERGY_MAX_FACTOR; } + + public static boolean allowTvmShanghai() { + return ALLOW_TVM_SHANGHAI; + } } 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..18eb543097b 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 @@ -96,7 +96,7 @@ public void validate(DelegateResourceParam param, Repository repo) throws Contra break; default: throw new ContractValidateException( - "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } byte[] receiverAddress = param.getReceiverAddress(); 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..c5c8fa91344 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 @@ -48,7 +48,7 @@ public void validate(FreezeBalanceParam param, Repository repo) throws ContractV break; default: throw new ContractValidateException( - "ResourceCode error,valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } // validate for delegating resource 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..b3dd258ae59 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 @@ -1,5 +1,11 @@ package org.tron.core.vm.nativecontract; +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_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.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; @@ -9,12 +15,6 @@ import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; import org.tron.core.vm.repository.Repository; -import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_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.protos.contract.Common.ResourceCode.BANDWIDTH; -import static org.tron.protos.contract.Common.ResourceCode.ENERGY; - @Slf4j(topic = "VMProcessor") public class FreezeBalanceV2Processor { @@ -50,16 +50,16 @@ public void validate(FreezeBalanceV2Param param, Repository repo) throws Contrac case TRON_POWER: if (!repo.getDynamicPropertiesStore().supportAllowNewResourceModel()) { throw new ContractValidateException( - "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } break; default: if (repo.getDynamicPropertiesStore().supportAllowNewResourceModel()) { throw new ContractValidateException( - "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); } else { throw new ContractValidateException( - "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } } } 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..d4cc2fcb8ce 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 @@ -1,6 +1,14 @@ package org.tron.core.vm.nativecontract; +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_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.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + import com.google.common.primitives.Bytes; +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; @@ -17,15 +25,6 @@ import org.tron.core.vm.nativecontract.param.UnDelegateResourceParam; import org.tron.core.vm.repository.Repository; -import java.util.Arrays; -import java.util.Objects; - -import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_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.protos.contract.Common.ResourceCode.BANDWIDTH; -import static org.tron.protos.contract.Common.ResourceCode.ENERGY; - @Slf4j(topic = "VMProcessor") public class UnDelegateResourceProcessor { @@ -84,7 +83,7 @@ public void validate(UnDelegateResourceParam param, Repository repo) throws Cont break; default: throw new ContractValidateException( - "ResourceCode error.valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java index 0eda888d3ca..211784d279b 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java @@ -65,8 +65,8 @@ public void validate(UnfreezeBalanceParam param, Repository repo) } break; default: - throw new ContractValidateException("ResourceCode error." - + "valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException("Unknown ResourceCode, " + + "valid ResourceCode[BANDWIDTH、ENERGY]"); } } else { switch (param.getResourceType()) { @@ -95,8 +95,8 @@ public void validate(UnfreezeBalanceParam param, Repository repo) } break; default: - throw new ContractValidateException("ResourceCode error." - + "valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException("Unknown ResourceCode, " + + "valid ResourceCode[BANDWIDTH、ENERGY]"); } } } diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java index f4d5c407373..56366bbdb0c 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java @@ -71,14 +71,14 @@ public void validate(UnfreezeBalanceV2Param param, Repository repo) throw new ContractValidateException("no frozenBalance(TRON_POWER)"); } } else { - throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、ENERGY]"); + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } break; default: if (dynamicStore.supportAllowNewResourceModel()) { - throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); } else { - throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、ENERGY]"); + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } } 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 3a0aaf21f70..90a59f53a36 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 @@ -17,7 +17,6 @@ import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; - import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -1815,9 +1814,9 @@ public boolean freeze(DataWord receiverAddress, DataWord frozenBalance, DataWord repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM Freeze: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM Freeze: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM Freeze: frozenBalance out of long range."); + logger.warn("TVM Freeze: frozenBalance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -1848,7 +1847,7 @@ public boolean unfreeze(DataWord receiverAddress, DataWord resourceType) { } return true; } catch (ContractValidateException e) { - logger.error("TVM Unfreeze: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM Unfreeze: validate failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -1911,9 +1910,9 @@ public boolean freezeBalanceV2(DataWord frozenBalance, DataWord resourceType) { repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM FreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM FreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM FreezeBalanceV2: frozenBalance out of long range."); + logger.warn("TVM FreezeBalanceV2: frozenBalance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -1947,9 +1946,9 @@ public boolean unfreezeBalanceV2(DataWord unfreezeBalance, DataWord resourceType } return true; } catch (ContractValidateException e) { - logger.error("TVM UnfreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM UnfreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM UnfreezeBalanceV2: balance out of long range."); + logger.warn("TVM UnfreezeBalanceV2: balance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -1978,9 +1977,9 @@ public long withdrawExpireUnfreeze() { } return expireUnfreezeBalance; } catch (ContractValidateException e) { - logger.error("TVM WithdrawExpireUnfreeze: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawExpireUnfreeze: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM WithdrawExpireUnfreeze: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawExpireUnfreeze: execute failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -2011,9 +2010,9 @@ public boolean cancelAllUnfreezeV2Action() { } return true; } catch (ContractValidateException e) { - logger.error("TVM CancelAllUnfreezeV2: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM CancelAllUnfreezeV2: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM CancelAllUnfreezeV2: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM CancelAllUnfreezeV2: execute failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -2045,9 +2044,9 @@ public boolean delegateResource( repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM DelegateResource: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM DelegateResource: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM DelegateResource: balance out of long range."); + logger.warn("TVM DelegateResource: balance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -2079,9 +2078,9 @@ public boolean unDelegateResource( repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM UnDelegateResource: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM UnDelegateResource: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM UnDelegateResource: balance out of long range."); + logger.warn("TVM UnDelegateResource: balance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -2114,7 +2113,7 @@ private Common.ResourceCode parseResourceCodeV2(DataWord resourceType) { return Common.ResourceCode.UNRECOGNIZED; } } catch (ArithmeticException e) { - logger.error("TVM ParseResourceCodeV2: invalid resource code: {}", resourceType.sValue()); + logger.warn("TVM ParseResourceCodeV2: invalid resource code: {}", resourceType.sValue()); return Common.ResourceCode.UNRECOGNIZED; } } @@ -2180,11 +2179,11 @@ public boolean voteWitness(int witnessArrayOffset, int witnessArrayLength, repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM VoteWitness: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM VoteWitness: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM VoteWitness: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM VoteWitness: execute failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM VoteWitness: int or long out of range. caused by: {}", e.getMessage()); + logger.warn("TVM VoteWitness: int or long out of range. caused by: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -2213,9 +2212,9 @@ public long withdrawReward() { } return allowance; } catch (ContractValidateException e) { - logger.error("TVM WithdrawReward: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawReward: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM WithdrawReward: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawReward: execute failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); diff --git a/build.gradle b/build.gradle index 82760ffd8cf..a4d23e2184e 100644 --- a/build.gradle +++ b/build.gradle @@ -44,7 +44,7 @@ subprojects { annotationProcessor 'org.projectlombok:lombok:1.18.12' testCompileOnly 'org.projectlombok:lombok:1.18.12' testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' - compile group: 'com.google.guava', name: 'guava', version: '24.1-jre' + compile group: 'com.google.guava', name: 'guava', version: '30.1-jre' compile "com.google.code.findbugs:jsr305:3.0.0" compile group: 'org.springframework', name: 'spring-context', version: '5.3.18' compile group: 'org.springframework', name: 'spring-tx', version: '5.3.18' @@ -70,6 +70,12 @@ subprojects { resolutionStrategy { force group: 'com.google.guava', name: 'guava', version: '30.1-jre' } + resolutionStrategy.eachDependency { details -> + // TODO if update grpc remove + if(details.requested.group == 'io.netty') { + details.useVersion "4.1.27.Final" + } + } } } @@ -82,3 +88,10 @@ task copyToParent(type: Copy) { build.finalizedBy(copyToParent) +gradle.buildFinished { + if (project.hasProperty('cleanSubBuild')) { + subprojects { + buildDir.deleteDir() + } + } +} diff --git a/chainbase/build.gradle b/chainbase/build.gradle index cac7efc6fa5..ed9911b0032 100644 --- a/chainbase/build.gradle +++ b/chainbase/build.gradle @@ -3,7 +3,7 @@ description = "chainbase – a decentralized database for blockchain." // Dependency versions // --------------------------------------- -def junitVersion = "4.12" +def junitVersion = "4.13.2" def mockitoVersion = "2.1.0" def testNgVersion = "6.11" def jacocoVersion = "0.8.0" diff --git a/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java b/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java index 54df4946297..2292f974c4b 100644 --- a/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java +++ b/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java @@ -142,22 +142,11 @@ private void openDatabase(Options dbOptions) throws IOException { if (!Files.isSymbolicLink(dbPath.getParent())) { Files.createDirectories(dbPath.getParent()); } - try { - database = factory.open(dbPath.toFile(), dbOptions); - if (!this.getDBName().startsWith("checkpoint")) { - logger.info("DB {} open success with writeBufferSize {} M, cacheSize {} M, maxOpenFiles {}.", - this.getDBName(), dbOptions.writeBufferSize() / 1024 / 1024, - dbOptions.cacheSize() / 1024 / 1024, dbOptions.maxOpenFiles()); - } - } catch (IOException e) { - if (e.getMessage().contains("Corruption:")) { - logger.warn("DB {} corruption detected, try to repair it.", this.getDBName(), e); - factory.repair(dbPath.toFile(), dbOptions); - logger.warn("DB {} corruption detected, repair done.", this.getDBName()); - database = factory.open(dbPath.toFile(), dbOptions); - } else { - throw e; - } + database = factory.open(dbPath.toFile(), dbOptions); + if (!this.getDBName().startsWith("checkpoint")) { + logger.info("DB {} open success with writeBufferSize {} M, cacheSize {} M, maxOpenFiles {}.", + this.getDBName(), dbOptions.writeBufferSize() / 1024 / 1024, + dbOptions.cacheSize() / 1024 / 1024, dbOptions.maxOpenFiles()); } } diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index 89ffcbd111f..c3db883a011 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -19,6 +19,7 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.store.DynamicPropertiesStore; @Slf4j(topic = "utils") public class ForkController { @@ -37,6 +38,17 @@ public class ForkController { public void init(ChainBaseManager manager) { this.manager = manager; + DynamicPropertiesStore store = manager.getDynamicPropertiesStore(); + int latestVersion = store.getLatestVersion(); + if (latestVersion == 0) { + for (ForkBlockVersionEnum version : ForkBlockVersionEnum.values()) { + int v = version.getValue(); + if (pass(v) && latestVersion < v) { + latestVersion = v; + } + } + store.saveLatestVersion(latestVersion); + } } public boolean pass(ForkBlockVersionEnum forkBlockVersionEnum) { @@ -87,7 +99,7 @@ private boolean passNew(int version) { } } return count >= Math - .ceil((double) versionEnum.getHardForkRate() * manager.getWitnesses().size() / 100); + .ceil((double) versionEnum.getHardForkRate() * stats.length / 100); } @@ -116,9 +128,9 @@ private boolean check(byte[] stats) { private void downgrade(int version, int slot) { for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); - if (versionValue > version) { + if (versionValue > version && !pass(versionValue)) { byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); - if (!check(stats) && Objects.nonNull(stats)) { + if (Objects.nonNull(stats)) { stats[slot] = VERSION_DOWNGRADE; manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } @@ -129,15 +141,13 @@ private void downgrade(int version, int slot) { private void upgrade(int version, int slotSize) { for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); - if (versionValue < version) { + if (versionValue < version && !pass(versionValue)) { byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); - if (!check(stats)) { - if (stats == null || stats.length == 0) { - stats = new byte[slotSize]; - } - Arrays.fill(stats, VERSION_UPGRADE); - manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); + if (stats == null || stats.length == 0) { + stats = new byte[slotSize]; } + Arrays.fill(stats, VERSION_UPGRADE); + manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } } } @@ -155,6 +165,10 @@ public synchronized void update(BlockCapsule blockCapsule) { return; } + if (manager.getDynamicPropertiesStore().getLatestVersion() >= version) { + return; + } + downgrade(version, slot); byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(version); @@ -162,8 +176,9 @@ public synchronized void update(BlockCapsule blockCapsule) { stats = new byte[witnesses.size()]; } - if (check(stats)) { + if (pass(version)) { upgrade(version, stats.length); + manager.getDynamicPropertiesStore().saveLatestVersion(version); return; } @@ -185,11 +200,12 @@ public synchronized void update(BlockCapsule blockCapsule) { } public synchronized void reset() { + int size = manager.getWitnessScheduleStore().getActiveWitnesses().size(); for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); if (Objects.nonNull(stats) && !pass(versionValue)) { - Arrays.fill(stats, VERSION_DOWNGRADE); + stats = new byte[size]; manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } } @@ -212,4 +228,5 @@ private ForkController getInstance() { return instance; } } + } diff --git a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java index c9ced891ee6..adf66527499 100644 --- a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java +++ b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java @@ -362,6 +362,9 @@ public boolean containBlockInMainChain(BlockId blockId) { } } + public BlockCapsule getKhaosDbHead(){ + return this.khaosDb.getHead(); + } /** * Get a BlockCapsule by id. 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 48593f5d36c..13f3cf576f1 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -42,8 +42,10 @@ import java.util.Map; import java.util.Objects; +import static java.lang.Math.ceil; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_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; @@ -1369,12 +1371,62 @@ public void setNewWindowSize(ResourceCode resourceCode, long newWindowSize) { public long getWindowSize(ResourceCode resourceCode) { long windowSize; + boolean windowOptimized; if (resourceCode == BANDWIDTH) { windowSize = this.account.getNetWindowSize(); + windowOptimized = this.account.getNetWindowOptimized(); } else { windowSize = this.account.getAccountResource().getEnergyWindowSize(); + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + if (windowSize == 0) { + return WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL; + } + if (windowOptimized) { + return windowSize < WINDOW_SIZE_PRECISION ? WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL : + windowSize / WINDOW_SIZE_PRECISION; + } else { + return windowSize; + } + } + + public long getWindowSizeV2(ResourceCode resourceCode) { + long windowSize; + boolean windowOptimized; + if (resourceCode == BANDWIDTH) { + windowSize = this.account.getNetWindowSize(); + windowOptimized = this.account.getNetWindowOptimized(); + } else { + windowSize = this.account.getAccountResource().getEnergyWindowSize(); + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + if (windowSize == 0) { + return WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL * WINDOW_SIZE_PRECISION; + } + if (windowOptimized) { + return windowSize; + } else { + return windowSize * WINDOW_SIZE_PRECISION; + } + } + + public boolean getWindowOptimized(ResourceCode resourceCode) { + boolean windowOptimized; + if (resourceCode == BANDWIDTH) { + windowOptimized = this.account.getNetWindowOptimized(); + } else { + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + return windowOptimized; + } + + public void setWindowOptimized(ResourceCode resourceCode, boolean windowOptimized) { + if (resourceCode == BANDWIDTH) { + this.account = this.account.toBuilder().setNetWindowOptimized(windowOptimized).build(); + } else { + this.account = this.account.toBuilder().setAccountResource(this.account.getAccountResource() + .toBuilder().setEnergyWindowOptimized(windowOptimized).build()).build(); } - return windowSize == 0 ? WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL : windowSize; } public long getLastConsumeTime(ResourceCode resourceCode) { @@ -1393,4 +1445,11 @@ public long getFrozenV2BalanceWithDelegated(ResourceCode resourceCode) { } } + public void setNewWindowSizeV2( ResourceCode resourceCode, long newWindowSize) { + this.setNewWindowSize(resourceCode, newWindowSize); + if (!this.getWindowOptimized(resourceCode)) { + this.setWindowOptimized(resourceCode, true); + } + } + } diff --git a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java index 2cef21e7617..7d003b6b0e4 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java @@ -69,6 +69,10 @@ public class ReceiptCapsule { @Setter private long callerEnergyWindowSize; + @Getter + @Setter + private long callerEnergyWindowSizeV2; + /** * Window size of caller after merging frozen energy */ @@ -83,6 +87,10 @@ public class ReceiptCapsule { @Setter private long originEnergyWindowSize; + @Getter + @Setter + private long originEnergyWindowSizeV2; + /** * Window size of origin after merging frozen energy */ diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java index 1b6bf0722d4..a33f445c15f 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -333,13 +333,13 @@ public static byte[] getOwner(Transaction.Contract contract) { Class clazz = TransactionFactory .getContract(contract.getType()); if (clazz == null) { - logger.error("not exist {}", contract.getType()); + logger.warn("not exist {}", contract.getType()); return new byte[0]; } GeneratedMessageV3 generatedMessageV3 = contractParameter.unpack(clazz); owner = ReflectUtils.getFieldValue(generatedMessageV3, OWNER_ADDRESS); if (owner == null) { - logger.error("not exist [{}] field,{}", OWNER_ADDRESS, clazz); + logger.warn("not exist [{}] field,{}", OWNER_ADDRESS, clazz); return new byte[0]; } break; diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java index 98bb23c4729..8ff3064b73c 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java @@ -3,6 +3,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.List; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.tron.core.exception.BadItemException; import org.tron.protos.Protocol.MarketOrderDetail; @@ -89,6 +90,15 @@ public void setWithdrawExpireAmount(long amount) { .setWithdrawExpireAmount(amount).build(); } + public Map getCancelUnfreezeV2AmountMap() { + return transactionResult.getCancelUnfreezeV2AmountMap(); + } + + public void putAllCancelUnfreezeV2AmountMap(Map map) { + this.transactionResult = this.transactionResult.toBuilder() + .putAllCancelUnfreezeV2Amount(map).build(); + } + public long getExchangeReceivedAmount() { return transactionResult.getExchangeReceivedAmount(); } diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java b/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java index 2d438229ee6..c9e0d30b1e6 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java @@ -100,6 +100,7 @@ public static TransactionInfoCapsule buildTransactionInfoInstance(TransactionCap builder.setExchangeId(programResult.getRet().getExchangeId()); builder.setWithdrawAmount(programResult.getRet().getWithdrawAmount()); builder.setWithdrawExpireAmount(programResult.getRet().getWithdrawExpireAmount()); + builder.putAllCancelUnfreezeV2Amount(programResult.getRet().getCancelUnfreezeV2AmountMap()); builder.setExchangeReceivedAmount(programResult.getRet().getExchangeReceivedAmount()); builder.setExchangeInjectAnotherAmount(programResult.getRet().getExchangeInjectAnotherAmount()); builder.setExchangeWithdrawAnotherAmount( 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 7603a25313a..87472b6212f 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -1,6 +1,9 @@ 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; import org.tron.common.utils.Commons; import org.tron.core.capsule.AccountCapsule; @@ -59,13 +62,16 @@ protected long increase(long lastUsage, long usage, long lastTime, long now, lon } public long recovery(AccountCapsule accountCapsule, ResourceCode resourceCode, - long lastUsage, long lastTime, long now) { + long lastUsage, long lastTime, long now) { long oldWindowSize = accountCapsule.getWindowSize(resourceCode); return increase(lastUsage, 0, lastTime, now, oldWindowSize); } public long increase(AccountCapsule accountCapsule, ResourceCode resourceCode, - long lastUsage, long usage, long lastTime, long now) { + long lastUsage, long usage, long lastTime, long now) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + return increaseV2(accountCapsule, resourceCode, lastUsage, usage, lastTime, now); + } long oldWindowSize = accountCapsule.getWindowSize(resourceCode); long averageLastUsage = divideCeil(lastUsage * this.precision, oldWindowSize); long averageUsage = divideCeil(usage * this.precision, this.windowSize); @@ -88,15 +94,50 @@ public long increase(AccountCapsule accountCapsule, ResourceCode resourceCode, return newUsage; } long remainWindowSize = oldWindowSize - (now - lastTime); - long newWindowSize = (remainWindowSize * remainUsage + this.windowSize * usage) - / newUsage; + long newWindowSize = getNewWindowSize(remainUsage, remainWindowSize, usage, + windowSize, newUsage); accountCapsule.setNewWindowSize(resourceCode, newWindowSize); } return newUsage; } + public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, + long lastUsage, long usage, long lastTime, long now) { + long oldWindowSizeV2 = accountCapsule.getWindowSizeV2(resourceCode); + long oldWindowSize = accountCapsule.getWindowSize(resourceCode); + long averageLastUsage = divideCeil(lastUsage * this.precision, oldWindowSize); + long averageUsage = divideCeil(usage * this.precision, this.windowSize); + + if (lastTime != now) { + if (lastTime + oldWindowSize > now) { + long delta = now - lastTime; + double decay = (oldWindowSize - delta) / (double) oldWindowSize; + averageLastUsage = Math.round(averageLastUsage * decay); + } else { + averageLastUsage = 0; + } + } + + long newUsage = getUsage(averageLastUsage, oldWindowSize, averageUsage, this.windowSize); + long remainUsage = getUsage(averageLastUsage, oldWindowSize); + if (remainUsage == 0) { + accountCapsule.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION); + return newUsage; + } + + long remainWindowSize = oldWindowSizeV2 - (now - lastTime) * WINDOW_SIZE_PRECISION; + long newWindowSize = divideCeil( + 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, - long transferUsage, ResourceCode resourceCode, long now) { + long transferUsage, ResourceCode resourceCode, long now) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + return unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now); + } long lastOwnerTime = owner.getLastConsumeTime(resourceCode); long ownerUsage = owner.getUsage(resourceCode); // Update itself first @@ -110,17 +151,49 @@ public long unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiv long newOwnerUsage = ownerUsage + transferUsage; // mean ownerUsage == 0 and transferUsage == 0 if (newOwnerUsage == 0) { - owner.setNewWindowSize(resourceCode, this.windowSize); + owner.setNewWindowSize(resourceCode, this.windowSize); return newOwnerUsage; } // calculate new windowSize - long newOwnerWindowSize = (ownerUsage * remainOwnerWindowSize + - transferUsage * remainReceiverWindowSize) - / newOwnerUsage; + long newOwnerWindowSize = getNewWindowSize(ownerUsage, remainOwnerWindowSize, transferUsage, + remainReceiverWindowSize, newOwnerUsage); owner.setNewWindowSize(resourceCode, newOwnerWindowSize); return newOwnerUsage; } + public long unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver, + long transferUsage, ResourceCode resourceCode, long now) { + long lastOwnerTime = owner.getLastConsumeTime(resourceCode); + long ownerUsage = owner.getUsage(resourceCode); + // Update itself first + ownerUsage = increase(owner, resourceCode, ownerUsage, 0, lastOwnerTime, now); + long newOwnerUsage = ownerUsage + transferUsage; + // mean ownerUsage == 0 and transferUsage == 0 + if (newOwnerUsage == 0) { + owner.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION); + return newOwnerUsage; + } + + long remainOwnerWindowSizeV2 = owner.getWindowSizeV2(resourceCode); + long remainReceiverWindowSizeV2 = receiver.getWindowSizeV2(resourceCode); + remainOwnerWindowSizeV2 = remainOwnerWindowSizeV2 < 0 ? 0 : remainOwnerWindowSizeV2; + remainReceiverWindowSizeV2 = remainReceiverWindowSizeV2 < 0 ? 0 : remainReceiverWindowSizeV2; + + // calculate new windowSize + long newOwnerWindowSize = + divideCeil( + ownerUsage * remainOwnerWindowSizeV2 + transferUsage * remainReceiverWindowSizeV2, + newOwnerUsage); + newOwnerWindowSize = Math.min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION); + owner.setNewWindowSizeV2(resourceCode, newOwnerWindowSize); + return newOwnerUsage; + } + + private long getNewWindowSize(long lastUsage, long lastWindowSize, long usage, + long windowSize, long newUsage) { + return (lastUsage * lastWindowSize + usage * windowSize) / newUsage; + } + private long divideCeil(long numerator, long denominator) { return (numerator / denominator) + ((numerator % denominator) > 0 ? 1 : 0); } diff --git a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java index c239639f019..e9c4feb7e18 100644 --- a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java +++ b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java @@ -2,6 +2,8 @@ import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE; import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CREATION_TYPE; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import java.util.Objects; import lombok.Getter; @@ -263,14 +265,16 @@ && getRuntimeResult().getException() == null && !getRuntimeResult().isRevert()) receipt.getOriginEnergyUsage(), receipt.getOriginEnergyWindowSize(), receipt.getOriginEnergyMergedUsage(), - receipt.getOriginEnergyMergedWindowSize()); + receipt.getOriginEnergyMergedWindowSize(), + receipt.getOriginEnergyWindowSizeV2()); } resetAccountUsage(caller, receipt.getCallerEnergyUsage(), receipt.getCallerEnergyWindowSize(), receipt.getCallerEnergyMergedUsage(), - receipt.getCallerEnergyMergedWindowSize()); + receipt.getCallerEnergyMergedWindowSize(), + receipt.getCallerEnergyWindowSizeV2()); } receipt.payEnergyBill( dynamicPropertiesStore, accountStore, forkController, @@ -282,8 +286,12 @@ && getRuntimeResult().getException() == null && !getRuntimeResult().isRevert()) } private void resetAccountUsage(AccountCapsule accountCap, - long usage, long size, long mergedUsage, long mergedSize) { - long currentSize = accountCap.getWindowSize(Common.ResourceCode.ENERGY); + long usage, long size, long mergedUsage, long mergedSize, long size2) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + resetAccountUsageV2(accountCap, usage, size, mergedUsage, mergedSize, size2); + return; + } + long currentSize = accountCap.getWindowSize(ENERGY); long currentUsage = accountCap.getEnergyUsage(); // Drop the pre consumed frozen energy long newArea = currentUsage * currentSize @@ -294,8 +302,24 @@ private void resetAccountUsage(AccountCapsule accountCap, long newUsage = Long.max(0, newArea / newSize); // Reset account usage and window size accountCap.setEnergyUsage(newUsage); - accountCap.setNewWindowSize(Common.ResourceCode.ENERGY, - newUsage == 0 ? 0L : newSize); + accountCap.setNewWindowSize(ENERGY, newUsage == 0 ? 0L : newSize); + } + + private void resetAccountUsageV2(AccountCapsule accountCap, + long usage, long size, long mergedUsage, long mergedSize, long size2) { + long currentSize = accountCap.getWindowSize(ENERGY); + long currentSize2 = accountCap.getWindowSizeV2(ENERGY); + long currentUsage = accountCap.getEnergyUsage(); + // Drop the pre consumed frozen energy + long newArea = currentUsage * currentSize - (mergedUsage * mergedSize - usage * size); + // If area merging happened during suicide, use the current window size + long newSize = mergedSize == currentSize ? size : currentSize; + long newSize2 = mergedSize == currentSize ? size2 : currentSize2; + // Calc new usage by fixed x-axes + long newUsage = Long.max(0, newArea / newSize); + // Reset account usage and window size + accountCap.setEnergyUsage(newUsage); + accountCap.setNewWindowSizeV2(ENERGY, newUsage == 0 ? 0L : newSize2); } public boolean checkNeedRetry() { @@ -354,7 +378,7 @@ public void deleteContract(byte[] address) { public static byte[] convertToTronAddress(byte[] address) { if (address.length == 20) { byte[] newAddress = new byte[21]; - byte[] temp = new byte[]{DecodeUtil.addressPreFixByte}; + byte[] temp = new byte[] {DecodeUtil.addressPreFixByte}; System.arraycopy(temp, 0, newAddress, 0, temp.length); System.arraycopy(address, 0, newAddress, temp.length, address.length); address = newAddress; diff --git a/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java b/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java index 2dcd370a656..c1da54d84f4 100644 --- a/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java +++ b/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java @@ -51,7 +51,8 @@ public abstract class TronStoreWithRevoking implements I @Autowired private DbStatService dbStatService; - private DB db; + @Getter + private final DB db; protected TronStoreWithRevoking(String dbName) { String dbEngine = CommonParameter.getInstance().getStorage().getDbEngine(); diff --git a/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java b/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java index 63e020ea1d6..71cf361b06a 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java @@ -86,7 +86,6 @@ public TxCacheDB(String name, RecentTransactionStore recentTransactionStore) { this.bloomFilters[1] = BloomFilter.create(Funnels.byteArrayFunnel(), MAX_BLOCK_SIZE * TRANSACTION_COUNT); - init(); } /** @@ -110,7 +109,7 @@ private void initCache() { System.currentTimeMillis() - start); } - private void init() { + public void init() { long size = recentTransactionStore.size(); if (size != MAX_BLOCK_SIZE) { // 0. load from persistentStore diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java index fe59a2737dd..230a812e093 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java @@ -16,6 +16,7 @@ import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; @@ -122,6 +123,7 @@ public void close() { exitThread.interrupt(); // help GC exitThread = null; + flushServices.values().forEach(ExecutorService::shutdown); } catch (Exception e) { logger.warn("exitThread interrupt error", e); } @@ -469,9 +471,10 @@ private void pruneCheckpoint() { if (cpList.size() < 3) { return; } + long latestTimestamp = Long.parseLong(cpList.get(cpList.size()-1)); for (String cp: cpList.subList(0, cpList.size()-3)) { long timestamp = Long.parseLong(cp); - if (System.currentTimeMillis() - timestamp < ONE_MINUTE_MILLS*2) { + if (latestTimestamp - timestamp <= ONE_MINUTE_MILLS*2) { break; } String checkpointPath = Paths.get(StorageUtils.getOutputDirectoryByDbName(CHECKPOINT_V2_DIR), @@ -506,6 +509,7 @@ private void checkV1() { } } recover(checkTmpStore); + logger.info("checkpoint v1 recover success"); unChecked = false; } @@ -520,7 +524,12 @@ private void checkV2() { return; } + long latestTimestamp = Long.parseLong(cpList.get(cpList.size()-1)); for (String cp: cpList) { + long timestamp = Long.parseLong(cp); + if (latestTimestamp - timestamp > ONE_MINUTE_MILLS*2) { + continue; + } TronDatabase checkPointV2Store = getCheckpointDB(cp); recover(checkPointV2Store); checkPointV2Store.close(); 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 d2870b45e2b..5f8c9ff89fc 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,7 @@ package org.tron.core.store; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; + import com.google.protobuf.ByteString; import java.util.Arrays; import java.util.Optional; @@ -14,7 +16,6 @@ import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.Parameter; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.exception.BadItemException; @@ -101,6 +102,7 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] STORAGE_EXCHANGE_TAX_RATE = "STORAGE_EXCHANGE_TAX_RATE".getBytes(); private static final String FORK_CONTROLLER = "FORK_CONTROLLER"; private static final String FORK_PREFIX = "FORK_VERSION_"; + private static final byte[] VERSION_NUMBER = "VERSION_NUMBER".getBytes(); //This value is only allowed to be 0, 1, -1 private static final byte[] REMOVE_THE_POWER_OF_THE_GR = "REMOVE_THE_POWER_OF_THE_GR".getBytes(); //This value is only allowed to be 0, 1, -1 @@ -206,6 +208,14 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID = "ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID".getBytes(); + private static final byte[] ALLOW_TVM_SHANGHAI = "ALLOW_TVM_SHANGHAI".getBytes(); + + private static final byte[] ALLOW_CANCEL_ALL_UNFREEZE_V2 = "ALLOW_CANCEL_ALL_UNFREEZE_V2" + .getBytes(); + + private static final byte[] MAX_DELEGATE_LOCK_PERIOD = + "MAX_DELEGATE_LOCK_PERIOD".getBytes(); + @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { super(dbName); @@ -2190,7 +2200,7 @@ public long getNextMaintenanceTime() { } public long getMaintenanceSkipSlots() { - return Parameter.ChainConstant.MAINTENANCE_SKIP_SLOTS; + return ChainConstant.MAINTENANCE_SKIP_SLOTS; } public void saveNextMaintenanceTime(long nextMaintenanceTime) { @@ -2216,6 +2226,9 @@ public void updateNextMaintenanceTime(long blockTime) { //The unit is trx public void addTotalNetWeight(long amount) { + if (amount == 0) { + return; + } long totalNetWeight = getTotalNetWeight(); totalNetWeight += amount; if (allowNewReward()) { @@ -2226,6 +2239,9 @@ public void addTotalNetWeight(long amount) { //The unit is trx public void addTotalEnergyWeight(long amount) { + if (amount == 0) { + return; + } long totalEnergyWeight = getTotalEnergyWeight(); totalEnergyWeight += amount; if (allowNewReward()) { @@ -2236,6 +2252,9 @@ public void addTotalEnergyWeight(long amount) { //The unit is trx public void addTotalTronPowerWeight(long amount) { + if (amount == 0) { + return; + } long totalWeight = getTotalTronPowerWeight(); totalWeight += amount; if (allowNewReward()) { @@ -2280,6 +2299,19 @@ public Boolean getForked(int version) { return value == null ? null : Boolean.valueOf(new String(value)); } + public void saveLatestVersion(int version) { + this.put(VERSION_NUMBER, new BytesCapsule(ByteArray.fromInt(version))); + } + + public int getLatestVersion() { + BytesCapsule data = getUnchecked(VERSION_NUMBER); + if (data == null) { + saveLatestVersion(0); + return 0; + } + return ByteArray.toInt(data.getData()); + } + /** * get allow protobuf number. */ @@ -2755,6 +2787,50 @@ public long getAllowOptimizedReturnValueOfChainId() { () -> new IllegalArgumentException(msg)); } + public void saveAllowTvmShangHai(long allowTvmShangHai) { + this.put(DynamicPropertiesStore.ALLOW_TVM_SHANGHAI, + new BytesCapsule(ByteArray.fromLong(allowTvmShangHai))); + } + + public long getAllowTvmShangHai() { + return Optional.ofNullable(getUnchecked(ALLOW_TVM_SHANGHAI)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowTvmShangHai()); + } + + public void saveAllowCancelAllUnfreezeV2(long allowCancelAllUnfreezeV2) { + this.put(DynamicPropertiesStore.ALLOW_CANCEL_ALL_UNFREEZE_V2, + new BytesCapsule(ByteArray.fromLong(allowCancelAllUnfreezeV2))); + } + + public long getAllowCancelAllUnfreezeV2() { + return Optional.ofNullable(getUnchecked(ALLOW_CANCEL_ALL_UNFREEZE_V2)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowCancelAllUnfreezeV2()); + } + + public boolean supportAllowCancelAllUnfreezeV2() { + return getAllowCancelAllUnfreezeV2() == 1L && getUnfreezeDelayDays() > 0; + } + + public void saveMaxDelegateLockPeriod(long maxDelegateLockPeriod) { + this.put(DynamicPropertiesStore.MAX_DELEGATE_LOCK_PERIOD, + new BytesCapsule(ByteArray.fromLong(maxDelegateLockPeriod))); + } + + public long getMaxDelegateLockPeriod() { + return Optional.ofNullable(getUnchecked(MAX_DELEGATE_LOCK_PERIOD)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(DELEGATE_PERIOD / 3000); + } + + public boolean supportMaxDelegateLockPeriod() { + return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / 3000) && getUnfreezeDelayDays() > 0; + } + private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); diff --git a/common/build.gradle b/common/build.gradle index fc17f99cd84..0ed13763a1e 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -35,7 +35,7 @@ repositories { } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'junit', name: 'junit', version: '4.13.2' compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4.1' compile "com.cedarsoftware:java-util:1.8.0" @@ -53,6 +53,13 @@ dependencies { compile 'org.aspectj:aspectjrt:1.8.13' compile 'org.aspectj:aspectjweaver:1.8.13' compile 'org.aspectj:aspectjtools:1.8.13' + compile group: 'io.github.tronprotocol', name: 'libp2p', version: '1.2.0',{ + exclude group: 'io.grpc', module: 'grpc-context' + exclude group: 'io.grpc', module: 'grpc-core' + exclude group: 'io.grpc', module: 'grpc-netty' + exclude group: 'com.google.protobuf', module: 'protobuf-java' + exclude group: 'com.google.protobuf', module: 'protobuf-java-util' + } compile project(":protocol") } diff --git a/common/src/main/java/org/tron/common/parameter/CommonParameter.java b/common/src/main/java/org/tron/common/parameter/CommonParameter.java index ab04ca3e7a4..0c8e6f74ee3 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -1,15 +1,11 @@ package org.tron.common.parameter; -import static org.tron.core.Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; - import com.beust.jcommander.Parameter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Set; - -import com.google.common.annotations.VisibleForTesting; import lombok.Getter; import lombok.Setter; import org.quartz.CronExpression; @@ -22,6 +18,7 @@ import org.tron.core.config.args.Overlay; import org.tron.core.config.args.SeedNode; import org.tron.core.config.args.Storage; +import org.tron.p2p.dns.update.PublishConfig; public class CommonParameter { @@ -30,6 +27,7 @@ public class CommonParameter { public static CommonParameter PARAMETER = new CommonParameter(); @Setter public static boolean ENERGY_LIMIT_HARD_FORK = false; + @Getter @Parameter(names = {"-c", "--config"}, description = "Config file (default:config.conf)") public String shellConfFileName = ""; @Getter @@ -142,6 +140,9 @@ public class CommonParameter { public boolean nodeDiscoveryPersist; @Getter @Setter + public boolean nodeEffectiveCheckEnable; + @Getter + @Setter public int nodeConnectionTimeout; @Getter @Setter @@ -163,6 +164,9 @@ public class CommonParameter { public int maxConnectionsWithSameIp; @Getter @Setter + public int maxTps; + @Getter + @Setter public int minParticipationRate; @Getter @Setter @@ -188,6 +192,19 @@ public class CommonParameter { @Getter @Setter public String p2pNodeId; + @Getter + @Setter + public boolean nodeEnableIpv6 = false; + @Getter + @Setter + public List dnsTreeUrls; + @Getter + @Setter + public PublishConfig dnsPublishConfig; + @Getter + @Setter + public long syncFetchBatchNum; + //If you are running a solidity node for java tron, this flag is set to true @Getter @Setter @@ -322,6 +339,9 @@ public class CommonParameter { public boolean isOpenFullTcpDisconnect; @Getter @Setter + public boolean nodeDetectEnable; + @Getter + @Setter public int allowMultiSign; @Getter @Setter @@ -398,6 +418,12 @@ public class CommonParameter { @Setter public RateLimiterInitialization rateLimiterInitialization; @Getter + @Setter + public int rateLimiterGlobalQps; + @Getter + @Setter + public int rateLimiterGlobalIpQps; + @Getter public DbBackupConfig dbBackupConfig; @Getter public RocksDbSettings rocksDBCustomSettings; @@ -405,6 +431,11 @@ public class CommonParameter { public GenesisBlock genesisBlock; @Getter @Setter + @Parameter(names = {"--p2p-disable"}, description = "Switch for p2p module initialization. " + + "(defalut: false)", arity = 1) + public boolean p2pDisable = false; + @Getter + @Setter public List activeNodes; @Getter @Setter @@ -608,6 +639,22 @@ public class CommonParameter { @Setter public long dynamicEnergyMaxFactor = 0L; + @Getter + @Setter + public boolean dynamicConfigEnable; + + @Getter + @Setter + public long dynamicConfigCheckInterval; + + @Getter + @Setter + public long allowTvmShangHai; + + @Getter + @Setter + public long allowCancelAllUnfreezeV2; + private static double calcMaxTimeRatio() { //return max(2.0, min(5.0, 5 * 4.0 / max(Runtime.getRuntime().availableProcessors(), 1))); return 5.0; diff --git a/common/src/main/java/org/tron/common/prometheus/MetricKeys.java b/common/src/main/java/org/tron/common/prometheus/MetricKeys.java index 800c5cd3c62..87ab6fae0a3 100644 --- a/common/src/main/java/org/tron/common/prometheus/MetricKeys.java +++ b/common/src/main/java/org/tron/common/prometheus/MetricKeys.java @@ -44,6 +44,7 @@ private Gauge() { public static class Histogram { public static final String HTTP_SERVICE_LATENCY = "tron:http_service_latency_seconds"; public static final String GRPC_SERVICE_LATENCY = "tron:grpc_service_latency_seconds"; + public static final String JSONRPC_SERVICE_LATENCY = "tron:jsonrpc_service_latency_seconds"; public static final String MINER_LATENCY = "tron:miner_latency_seconds"; public static final String PING_PONG_LATENCY = "tron:ping_pong_latency_seconds"; public static final String VERIFY_SIGN_LATENCY = "tron:verify_sign_latency_seconds"; diff --git a/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java b/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java index 10cbf1d2979..556db10feb5 100644 --- a/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java +++ b/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java @@ -17,6 +17,8 @@ public class MetricsHistogram { "url"); init(MetricKeys.Histogram.GRPC_SERVICE_LATENCY, "Grpc Service latency.", "endpoint"); + init(MetricKeys.Histogram.JSONRPC_SERVICE_LATENCY, "JsonRpc Service latency.", + "method"); init(MetricKeys.Histogram.MINER_LATENCY, "miner latency.", "miner"); init(MetricKeys.Histogram.PING_PONG_LATENCY, "node ping pong latency."); diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 408782752f2..dea5a2534b9 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -83,15 +83,18 @@ public class Constant { public static final String BLOCK_NEED_SYNC_CHECK = "block.needSyncCheck"; public static final String NODE_DISCOVERY_ENABLE = "node.discovery.enable"; public static final String NODE_DISCOVERY_PERSIST = "node.discovery.persist"; + public static final String NODE_EFFECTIVE_CHECK_ENABLE = "node.effectiveCheckEnable"; public static final String NODE_CONNECTION_TIMEOUT = "node.connection.timeout"; public static final String NODE_FETCH_BLOCK_TIMEOUT = "node.fetchBlock.timeout"; public static final String NODE_CHANNEL_READ_TIMEOUT = "node.channel.read.timeout"; public static final String NODE_MAX_CONNECTIONS = "node.maxConnections"; public static final String NODE_MIN_CONNECTIONS = "node.minConnections"; public static final String NODE_MIN_ACTIVE_CONNECTIONS = "node.minActiveConnections"; + public static final String NODE_SYNC_FETCH_BATCH_NUM = "node.syncFetchBatchNum"; public static final String NODE_MAX_ACTIVE_NODES = "node.maxActiveNodes"; public static final String NODE_MAX_ACTIVE_NODES_WITH_SAME_IP = "node.maxActiveNodesWithSameIp"; + public static final String NODE_MAX_TPS = "node.maxTps"; public static final String NODE_CONNECT_FACTOR = "node.connectFactor"; public static final String NODE_ACTIVE_CONNECT_FACTOR = "node.activeConnectFactor"; @@ -103,6 +106,22 @@ public class Constant { public static final String NODE_P2P_PING_INTERVAL = "node.p2p.pingInterval"; public static final String NODE_P2P_VERSION = "node.p2p.version"; + public static final String NODE_ENABLE_IPV6 = "node.enableIpv6"; + public static final String NODE_DNS_TREE_URLS = "node.dns.treeUrls"; + public static final String NODE_DNS_PUBLISH = "node.dns.publish"; + public static final String NODE_DNS_DOMAIN = "node.dns.dnsDomain"; + public static final String NODE_DNS_CHANGE_THRESHOLD = "node.dns.changeThreshold"; + public static final String NODE_DNS_MAX_MERGE_SIZE = "node.dns.maxMergeSize"; + public static final String NODE_DNS_PRIVATE = "node.dns.dnsPrivate"; + public static final String NODE_DNS_KNOWN_URLS = "node.dns.knownUrls"; + public static final String NODE_DNS_STATIC_NODES = "node.dns.staticNodes"; + public static final String NODE_DNS_SERVER_TYPE = "node.dns.serverType"; + public static final String NODE_DNS_ACCESS_KEY_ID = "node.dns.accessKeyId"; + public static final String NODE_DNS_ACCESS_KEY_SECRET = "node.dns.accessKeySecret"; + public static final String NODE_DNS_ALIYUN_ENDPOINT = "node.dns.aliyunDnsEndpoint"; + public static final String NODE_DNS_AWS_REGION = "node.dns.awsRegion"; + public static final String NODE_DNS_AWS_HOST_ZONE_ID = "node.dns.awsHostZoneId"; + public static final String NODE_RPC_PORT = "node.rpc.port"; public static final String NODE_RPC_SOLIDITY_PORT = "node.rpc.solidityPort"; public static final String NODE_RPC_PBFT_PORT = "node.rpc.PBFTPort"; @@ -175,6 +194,8 @@ public class Constant { public static final String NODE_IS_OPEN_FULL_TCP_DISCONNECT = "node.isOpenFullTcpDisconnect"; + public static final String NODE_DETECT_ENABLE = "node.nodeDetectEnable"; + public static final String NODE_MAX_TRANSACTION_PENDING_SIZE = "node.maxTransactionPendingSize"; public static final String NODE_PENDING_TRANSACTION_TIMEOUT = "node.pendingTransactionTimeout"; @@ -235,6 +256,10 @@ public class Constant { public static final String RATE_LIMITER = "rate.limiter"; + public static final String RATE_LIMITER_GLOBAL_QPS = "rate.limiter.global.qps"; + + public static final String RATE_LIMITER_GLOBAL_IP_QPS = "rate.limiter.global.ip.qps"; + public static final String COMMITTEE_CHANGED_DELEGATION = "committee.changedDelegation"; public static final String CRYPTO_ENGINE = "crypto.engine"; @@ -343,4 +368,9 @@ public class Constant { public static final String NODE_SHUTDOWN_BLOCK_COUNT = "node.shutdown.BlockCount"; public static final String BLOCK_CACHE_TIMEOUT = "node.blockCacheTimeout"; + + public static final String DYNAMIC_CONFIG_ENABLE = "node.dynamicConfig.enable"; + public static final String DYNAMIC_CONFIG_CHECK_INTERVAL = "node.dynamicConfig.checkInterval"; + + public static final String COMMITTEE_ALLOW_TVM_SHANGHAI = "committee.allowTvmShangHai"; } 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 7116e1e7141..6bbc66846bd 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -21,7 +21,8 @@ public enum ForkBlockVersionEnum { VERSION_4_5(24, 1596780000000L, 80), VERSION_4_6(25, 1596780000000L, 80), VERSION_4_7(26, 1596780000000L, 80), - VERSION_4_7_1(27, 1596780000000L, 80); + VERSION_4_7_1(27, 1596780000000L, 80), + VERSION_4_7_2(28, 1596780000000L, 80); // if add a version, modify BLOCK_VERSION simultaneously @Getter @@ -70,11 +71,12 @@ public class ChainConstant { public static final int SINGLE_REPEAT = 1; public static final int BLOCK_FILLED_SLOTS_NUMBER = 128; public static final int MAX_FROZEN_NUMBER = 1; - public static final int BLOCK_VERSION = 27; + public static final int BLOCK_VERSION = 28; public static final long FROZEN_PERIOD = 86_400_000L; public static final long DELEGATE_PERIOD = 3 * 86_400_000L; 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 class NodeConstant { diff --git a/common/src/main/java/org/tron/core/config/args/SeedNode.java b/common/src/main/java/org/tron/core/config/args/SeedNode.java index 6597110074d..9420d969789 100644 --- a/common/src/main/java/org/tron/core/config/args/SeedNode.java +++ b/common/src/main/java/org/tron/core/config/args/SeedNode.java @@ -1,5 +1,6 @@ package org.tron.core.config.args; +import java.net.InetSocketAddress; import java.util.List; import lombok.Getter; import lombok.Setter; @@ -8,5 +9,5 @@ public class SeedNode { @Getter @Setter - private List ipList; + private List addressList; } diff --git a/common/src/main/java/org/tron/core/exception/BadBlockException.java b/common/src/main/java/org/tron/core/exception/BadBlockException.java index e3308819d22..224ffc253ee 100644 --- a/common/src/main/java/org/tron/core/exception/BadBlockException.java +++ b/common/src/main/java/org/tron/core/exception/BadBlockException.java @@ -2,6 +2,8 @@ public class BadBlockException extends TronException { + private TypeEnum type = TypeEnum.DEFAULT; + public BadBlockException() { super(); } @@ -9,4 +11,28 @@ public BadBlockException() { public BadBlockException(String message) { super(message); } + + public BadBlockException(TypeEnum type, String message) { + super(message); + this.type = type; + } + + public TypeEnum getType() { + return type; + } + + public enum TypeEnum { + CALC_MERKLE_ROOT_FAILED(1), + DEFAULT(100); + + private Integer value; + + TypeEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + } } diff --git a/common/src/main/java/org/tron/core/exception/P2pException.java b/common/src/main/java/org/tron/core/exception/P2pException.java index d566b833d59..00d82e9fbf7 100644 --- a/common/src/main/java/org/tron/core/exception/P2pException.java +++ b/common/src/main/java/org/tron/core/exception/P2pException.java @@ -50,6 +50,8 @@ public enum TypeEnum { TRX_EXE_FAILED(12, "trx exe failed"), DB_ITEM_NOT_FOUND(13, "DB item not found"), PROTOBUF_ERROR(14, "protobuf inconsistent"), + BLOCK_SIGN_ERROR(15, "block sign error"), + BLOCK_MERKLE_ERROR(16, "block merkle error"), DEFAULT(100, "default exception"); diff --git a/consensus/build.gradle b/consensus/build.gradle index c2393064d46..c22e961572e 100644 --- a/consensus/build.gradle +++ b/consensus/build.gradle @@ -2,7 +2,7 @@ description = "consensus – a distributed consensus arithmetic for blockchain." // Dependency versions // --------------------------------------- -def junitVersion = "4.12" +def junitVersion = "4.13.2" def mockitoVersion = "2.1.0" def testNgVersion = "6.11" def slf4jVersion = "1.7.25" diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java index 8d12ecbd3f4..2f42524e03e 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftManager.java @@ -44,7 +44,7 @@ public void blockPrePrepare(BlockCapsule block, long epoch) { } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - for (Miner miner : pbftMessageHandle.getSrMinerList()) { + for (Miner miner : pbftMessageHandle.getSrMinerList(epoch)) { doAction(PbftMessage.prePrepareBlockMsg(block, epoch, miner)); } } else { @@ -59,7 +59,7 @@ public void srPrePrepare(BlockCapsule block, List currentWitness, lo } if (!pbftMessageHandle.isSyncing()) { if (Param.getInstance().isEnable()) { - for (Miner miner : pbftMessageHandle.getSrMinerList()) { + for (Miner miner : pbftMessageHandle.getSrMinerList(epoch)) { doAction(PbftMessage.prePrepareSRLMsg(block, currentWitness, epoch, miner)); } } else { diff --git a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java index f2ef7b43ef0..ea7b00802b2 100644 --- a/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java +++ b/consensus/src/main/java/org/tron/consensus/pbft/PbftMessageHandle.java @@ -91,9 +91,15 @@ public void close() { } } - public List getSrMinerList() { + public List getSrMinerList(long epoch) { + List compareList; + if (epoch > maintenanceManager.getBeforeMaintenanceTime()) { + compareList = maintenanceManager.getCurrentWitness(); + } else { + compareList = maintenanceManager.getBeforeWitness(); + } return Param.getInstance().getMiners().stream() - .filter(miner -> chainBaseManager.getWitnesses().contains(miner.getWitnessAddress())) + .filter(miner -> compareList.contains(miner.getWitnessAddress())) .collect(Collectors.toList()); } @@ -115,10 +121,11 @@ public void onPrePrepare(PbftMessage message) { // checkPrepareMsgCache(key); //Into the preparation phase, if not the sr node does not need to be prepared - if (!checkIsCanSendMsg(message)) { + long epoch = message.getPbftMessage().getRawData().getEpoch(); + if (!checkIsCanSendMsg(epoch)) { return; } - for (Miner miner : getSrMinerList()) { + for (Miner miner : getSrMinerList(epoch)) { PbftMessage paMessage = message.buildPrePareMessage(miner); forwardMessage(paMessage); try { @@ -153,7 +160,8 @@ public synchronized void onPrepare(PbftMessage message) { pareVoteMap.put(key, message); // checkCommitMsgCache(message.getNo()); - if (!checkIsCanSendMsg(message)) { + long epoch = message.getPbftMessage().getRawData().getEpoch(); + if (!checkIsCanSendMsg(epoch)) { return; } //The number of votes plus 1 @@ -162,7 +170,7 @@ public synchronized void onPrepare(PbftMessage message) { if (agCou >= Param.getInstance().getAgreeNodeCount()) { agreePare.remove(message.getDataKey()); //Entering the submission stage - for (Miner miner : getSrMinerList()) { + for (Miner miner : getSrMinerList(epoch)) { PbftMessage cmMessage = message.buildCommitMessage(miner); doneMsg.put(message.getNo(), cmMessage); forwardMessage(cmMessage); @@ -239,19 +247,11 @@ private void checkCommitMsgCache(String key) { } } - public boolean checkIsCanSendMsg(PbftMessage msg) { + public boolean checkIsCanSendMsg(long epoch) { if (!Param.getInstance().isEnable()) {//is witness return false; } - ByteString publicKey = Param.getInstance().getMiner().getPrivateKeyAddress(); - List compareList; - long epoch = msg.getPbftMessage().getRawData().getEpoch(); - if (epoch > maintenanceManager.getBeforeMaintenanceTime()) { - compareList = maintenanceManager.getCurrentWitness(); - } else { - compareList = maintenanceManager.getBeforeWitness(); - } - if (!compareList.contains(publicKey)) { + if (getSrMinerList(epoch).isEmpty()) { return false; } return !isSyncing(); diff --git a/crypto/build.gradle b/crypto/build.gradle index 9d90368814d..19ae8e805fe 100644 --- a/crypto/build.gradle +++ b/crypto/build.gradle @@ -11,7 +11,7 @@ repositories { } dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'junit', name: 'junit', version: '4.13.2' compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' compile project(":common") } diff --git a/docs/implement-a-customized-actuator-en.md b/docs/implement-a-customized-actuator-en.md index b6f9124b64f..7152a4a67e4 100644 --- a/docs/implement-a-customized-actuator-en.md +++ b/docs/implement-a-customized-actuator-en.md @@ -234,7 +234,7 @@ public class SumActuatorTest { appTest.startServices(); appTest.startup(); channelFull = ManagedChannelBuilder.forTarget(serviceNode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } diff --git a/docs/implement-a-customized-actuator-zh.md b/docs/implement-a-customized-actuator-zh.md index a248aa5c18b..3c60584c599 100644 --- a/docs/implement-a-customized-actuator-zh.md +++ b/docs/implement-a-customized-actuator-zh.md @@ -236,7 +236,7 @@ public class SumActuatorTest { appTest.startServices(); appTest.startup(); channelFull = ManagedChannelBuilder.forTarget(serviceNode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } diff --git a/framework/build.gradle b/framework/build.gradle index 4cd08614032..fbe1fc0308b 100644 --- a/framework/build.gradle +++ b/framework/build.gradle @@ -40,7 +40,7 @@ dependencies { //local libraries compile fileTree(dir: 'libs', include: '*.jar') // end local libraries - testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'junit', name: 'junit', version: '4.13.2' testCompile group: 'org.mockito', name: 'mockito-core', version: '2.13.0' testCompile group: 'org.hamcrest', name: 'hamcrest-junit', version: '1.0.0.1' @@ -48,15 +48,13 @@ dependencies { compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' - compile group: 'io.github.tronprotocol', name: 'libp2p', version: '0.1.4' - compile group: 'com.typesafe', name: 'config', version: '1.3.2' compile "com.cedarsoftware:java-util:1.8.0" compile group: 'com.beust', name: 'jcommander', version: '1.72' - compile group: 'junit', name: 'junit', version: '4.12' + compile group: 'junit', name: 'junit', version: '4.13.2' compile group: 'net.jcip', name: 'jcip-annotations', version: '1.0' @@ -88,7 +86,9 @@ dependencies { compile "io.vavr:vavr:0.9.2" compile group: 'org.pf4j', name: 'pf4j', version: '2.5.0' - compile group: 'org.zeromq', name: 'jeromq', version: '0.5.0' + testImplementation group: 'org.springframework', name: 'spring-test', version: '5.2.0.RELEASE' + + compile group: 'org.zeromq', name: 'jeromq', version: '0.5.3' compile project(":chainbase") compile project(":protocol") compile project(":actuator") @@ -153,37 +153,12 @@ test { exclude 'org/tron/common/runtime/vm/WithdrawRewardTest.class' } maxHeapSize = "1024m" -} - -task stest(type: Test) { - - useTestNG { - suites(file('src/test/resources/testng.xml')) - parallel 'tests' - threadCount 4 - - } - - testLogging { - exceptionFormat = 'full' - showStackTraces = "true" - } - - jacoco { - destinationFile = file("$buildDir/jacoco/jacocoTest.exec") - classDumpDir = file("$buildDir/jacoco/classpathdumps") + doFirst { + forkEvery = 100 + jvmArgs "-XX:MetaspaceSize=128m","-XX:MaxMetaspaceSize=256m", "-XX:+UseG1GC" } } -task dailyBuild(type: Test) { - useTestNG { - suites(file('src/test/resources/daily-build.xml')) - parallel 'tests' - threadCount 1 - } -} - - jacocoTestReport { reports { xml.enabled true diff --git a/framework/src/main/java/org/tron/common/application/ApplicationImpl.java b/framework/src/main/java/org/tron/common/application/ApplicationImpl.java index 235ece75835..0e38e97baaf 100644 --- a/framework/src/main/java/org/tron/common/application/ApplicationImpl.java +++ b/framework/src/main/java/org/tron/common/application/ApplicationImpl.java @@ -7,6 +7,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.core.ChainBaseManager; import org.tron.core.config.args.Args; +import org.tron.core.config.args.DynamicArgs; import org.tron.core.consensus.ConsensusService; import org.tron.core.db.Manager; import org.tron.core.metrics.MetricsUtil; @@ -32,6 +33,9 @@ public class ApplicationImpl implements Application { @Autowired private ConsensusService consensusService; + @Autowired + private DynamicArgs dynamicArgs; + @Override public void setOptions(Args args) { // not used @@ -57,17 +61,18 @@ public void initServices(CommonParameter parameter) { * start up the app. */ public void startup() { - if (!Args.getInstance().isSolidityNode()) { + if ((!Args.getInstance().isSolidityNode()) && (!Args.getInstance().isP2pDisable())) { tronNetService.start(); } consensusService.start(); MetricsUtil.init(); + dynamicArgs.init(); } @Override public void shutdown() { logger.info("******** start to shutdown ********"); - if (!Args.getInstance().isSolidityNode()) { + if (!Args.getInstance().isSolidityNode() && (!Args.getInstance().p2pDisable)) { tronNetService.close(); } consensusService.stop(); @@ -80,6 +85,7 @@ public void shutdown() { dbManager.stopRePushTriggerThread(); EventPluginLoader.getInstance().stopPlugin(); dbManager.stopFilterProcessThread(); + dynamicArgs.close(); logger.info("******** end to shutdown ********"); FullNode.shutDownSign = true; } diff --git a/framework/src/main/java/org/tron/common/backup/message/Message.java b/framework/src/main/java/org/tron/common/backup/message/Message.java index 8f09a452877..cd1a2669427 100644 --- a/framework/src/main/java/org/tron/common/backup/message/Message.java +++ b/framework/src/main/java/org/tron/common/backup/message/Message.java @@ -20,7 +20,8 @@ public Message(UdpMessageTypeEnum type, byte[] data) { public static Node getNode(Endpoint endpoint) { Node node = new Node(endpoint.getNodeId().toByteArray(), - ByteArray.toStr(endpoint.getAddress().toByteArray()), endpoint.getPort()); + ByteArray.toStr(endpoint.getAddress().toByteArray()), + ByteArray.toStr(endpoint.getAddressIpv6().toByteArray()), endpoint.getPort()); return node; } diff --git a/framework/src/main/java/org/tron/common/client/DatabaseGrpcClient.java b/framework/src/main/java/org/tron/common/client/DatabaseGrpcClient.java index b83c7235900..f3650bfd2be 100644 --- a/framework/src/main/java/org/tron/common/client/DatabaseGrpcClient.java +++ b/framework/src/main/java/org/tron/common/client/DatabaseGrpcClient.java @@ -15,14 +15,14 @@ public class DatabaseGrpcClient { public DatabaseGrpcClient(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port) - .usePlaintext(true) + .usePlaintext() .build(); databaseBlockingStub = DatabaseGrpc.newBlockingStub(channel); } public DatabaseGrpcClient(String host) { channel = ManagedChannelBuilder.forTarget(host) - .usePlaintext(true) + .usePlaintext() .build(); databaseBlockingStub = DatabaseGrpc.newBlockingStub(channel); } diff --git a/framework/src/main/java/org/tron/common/client/WalletGrpcClient.java b/framework/src/main/java/org/tron/common/client/WalletGrpcClient.java index 9d3b5797e20..d28df0e7c77 100644 --- a/framework/src/main/java/org/tron/common/client/WalletGrpcClient.java +++ b/framework/src/main/java/org/tron/common/client/WalletGrpcClient.java @@ -29,14 +29,14 @@ public class WalletGrpcClient { public WalletGrpcClient(String host, int port) { channel = ManagedChannelBuilder.forAddress(host, port) - .usePlaintext(true) + .usePlaintext() .build(); walletBlockingStub = WalletGrpc.newBlockingStub(channel); } public WalletGrpcClient(String host) { channel = ManagedChannelBuilder.forTarget(host) - .usePlaintext(true) + .usePlaintext() .build(); walletBlockingStub = WalletGrpc.newBlockingStub(channel); } diff --git a/framework/src/main/java/org/tron/common/logsfilter/nativequeue/NativeMessageQueue.java b/framework/src/main/java/org/tron/common/logsfilter/nativequeue/NativeMessageQueue.java index cf2fe6dce0a..c0a115620c2 100644 --- a/framework/src/main/java/org/tron/common/logsfilter/nativequeue/NativeMessageQueue.java +++ b/framework/src/main/java/org/tron/common/logsfilter/nativequeue/NativeMessageQueue.java @@ -59,7 +59,7 @@ public void stop() { } public void publishTrigger(String data, String topic) { - if (Objects.isNull(publisher) || Objects.isNull(context.isClosed()) || context.isClosed()) { + if (Objects.isNull(publisher) || Objects.isNull(context) || context.isClosed()) { return; } diff --git a/framework/src/main/java/org/tron/core/Wallet.java b/framework/src/main/java/org/tron/core/Wallet.java index 295cb7d5bc1..b866ab54001 100755 --- a/framework/src/main/java/org/tron/core/Wallet.java +++ b/framework/src/main/java/org/tron/core/Wallet.java @@ -110,6 +110,7 @@ import org.tron.common.utils.ByteUtil; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; import org.tron.common.utils.WalletUtil; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; @@ -121,6 +122,7 @@ import org.tron.common.zksnark.LibrustzcashParam.SpendSigParams; import org.tron.consensus.ConsensusDelegate; import org.tron.core.actuator.Actuator; +import org.tron.core.actuator.ActuatorConstant; import org.tron.core.actuator.ActuatorFactory; import org.tron.core.actuator.UnfreezeBalanceV2Actuator; import org.tron.core.actuator.VMActuator; @@ -533,6 +535,9 @@ public GrpcAPI.Return broadcastTransaction(Transaction signedTransaction) { if (chainBaseManager.getDynamicPropertiesStore().supportVM()) { trx.resetResult(); } + if (trx.getInstance().getRawData().getContractCount() == 0) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } dbManager.pushTransaction(trx); int num = tronNetService.fastBroadcastTransaction(message); if (num == 0 && minEffectiveConnection != 0) { @@ -583,7 +588,7 @@ public GrpcAPI.Return broadcastTransaction(Transaction signedTransaction) { .setMessage(ByteString.copyFromUtf8("Transaction expired")) .build(); } catch (Exception e) { - logger.error(BROADCAST_TRANS_FAILED, txID, e.getMessage()); + logger.warn("Broadcast transaction {} failed", txID, e); return builder.setResult(false).setCode(response_code.OTHER_ERROR) .setMessage(ByteString.copyFromUtf8("Error: " + e.getMessage())) .build(); @@ -1315,6 +1320,21 @@ public Protocol.ChainParameters getChainParameters() { .setValue(dbManager.getDynamicPropertiesStore().getDynamicEnergyMaxFactor()) .build()); + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowTvmShangHai") + .setValue(dbManager.getDynamicPropertiesStore().getAllowTvmShangHai()) + .build()); + + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getAllowCancelAllUnfreezeV2") + .setValue(dbManager.getDynamicPropertiesStore().getAllowCancelAllUnfreezeV2()) + .build()); + + builder.addChainParameter(Protocol.ChainParameters.ChainParameter.newBuilder() + .setKey("getMaxDelegateLockPeriod") + .setValue(dbManager.getDynamicPropertiesStore().getMaxDelegateLockPeriod()) + .build()); + return builder.build(); } @@ -1708,7 +1728,7 @@ public Proposal getProposalById(ByteString proposalId) { proposalCapsule = chainBaseManager.getProposalStore() .get(proposalId.toByteArray()); } catch (StoreException e) { - logger.error(e.getMessage()); + logger.warn(e.getMessage()); } if (proposalCapsule != null) { return proposalCapsule.getInstance(); @@ -2626,7 +2646,7 @@ public TransactionInfoList getTransactionInfoByBlockNum(long blockNum) { } } } catch (BadItemException | ItemNotFoundException e) { - logger.error(e.getMessage()); + logger.warn(e.getMessage()); } return transactionInfoList.build(); @@ -2634,13 +2654,16 @@ public TransactionInfoList getTransactionInfoByBlockNum(long blockNum) { public NodeList listNodes() { NodeList.Builder nodeListBuilder = NodeList.newBuilder(); - TronNetService.getP2pService().getConnectableNodes().forEach(node -> { - nodeListBuilder.addNodes(Node.newBuilder().setAddress( - Address.newBuilder() - .setHost(ByteString - .copyFrom(ByteArray.fromString(node.getHost()))) - .setPort(node.getPort()))); - }); + if (!Args.getInstance().p2pDisable) { + TronNetService.getP2pService().getConnectableNodes().forEach(node -> { + nodeListBuilder.addNodes(Node.newBuilder().setAddress( + Address.newBuilder() + .setHost(ByteString + .copyFrom(ByteArray.fromString( + node.getPreferInetSocketAddress().getAddress().getHostAddress()))) + .setPort(node.getPort()))); + }); + } return nodeListBuilder.build(); } @@ -2655,7 +2678,7 @@ public MarketOrder getMarketOrderById(ByteString orderId) { try { return marketOrderStore.get(orderId.toByteArray()).getInstance(); } catch (ItemNotFoundException e) { - logger.error("orderId = " + orderId.toString() + " not found"); + logger.warn("orderId = {} not found", orderId); throw new IllegalStateException("order not found in store"); } @@ -2691,7 +2714,7 @@ public MarketOrderList getMarketOrderByAccount(ByteString accountAddress) { marketOrderListBuilder .addOrders(orderCapsule.getInstance()); } catch (ItemNotFoundException e) { - logger.error("orderId = " + orderId.toString() + " not found"); + logger.warn("orderId = {} not found", orderId); throw new IllegalStateException("order not found in store"); } } @@ -2837,7 +2860,7 @@ public Transaction triggerContract(TriggerSmartContract triggerSmartContract.getData().toByteArray()); if (isConstant(abi, selector)) { - return callConstantContract(trxCap, builder, retBuilder); + return callConstantContract(trxCap, builder, retBuilder, false); } else { return trxCap.getInstance(); } @@ -2955,13 +2978,19 @@ private Transaction cleanContextAndTriggerConstantContract( txExtBuilder.clear(); txRetBuilder.clear(); transaction = triggerConstantContract( - triggerSmartContract, txCap, txExtBuilder, txRetBuilder); + triggerSmartContract, txCap, txExtBuilder, txRetBuilder, true); return transaction; } public Transaction triggerConstantContract(TriggerSmartContract triggerSmartContract, TransactionCapsule trxCap, Builder builder, Return.Builder retBuilder) throws ContractValidateException, ContractExeException, HeaderNotFound, VMIllegalException { + return triggerConstantContract(triggerSmartContract, trxCap, builder, retBuilder, false); + } + + public Transaction triggerConstantContract(TriggerSmartContract triggerSmartContract, + TransactionCapsule trxCap, Builder builder, Return.Builder retBuilder, boolean isEstimating) + throws ContractValidateException, ContractExeException, HeaderNotFound, VMIllegalException { if (triggerSmartContract.getContractAddress().isEmpty()) { // deploy contract CreateSmartContract.Builder deployBuilder = CreateSmartContract.newBuilder(); @@ -2986,11 +3015,11 @@ public Transaction triggerConstantContract(TriggerSmartContract triggerSmartCont throw new ContractValidateException("Smart contract is not exist."); } } - return callConstantContract(trxCap, builder, retBuilder); + return callConstantContract(trxCap, builder, retBuilder, isEstimating); } public Transaction callConstantContract(TransactionCapsule trxCap, - Builder builder, Return.Builder retBuilder) + Builder builder, Return.Builder retBuilder, boolean isEstimating) throws ContractValidateException, ContractExeException, HeaderNotFound, VMIllegalException { if (!Args.getInstance().isSupportConstant()) { @@ -3006,7 +3035,8 @@ public Transaction callConstantContract(TransactionCapsule trxCap, headBlock = blockCapsuleList.get(0).getInstance(); } - TransactionContext context = new TransactionContext(new BlockCapsule(headBlock), trxCap, + BlockCapsule headBlockCapsule = new BlockCapsule(headBlock); + TransactionContext context = new TransactionContext(headBlockCapsule, trxCap, StoreFactory.getInstance(), true, false); VMActuator vmActuator = new VMActuator(true); @@ -3014,9 +3044,10 @@ public Transaction callConstantContract(TransactionCapsule trxCap, vmActuator.execute(context); ProgramResult result = context.getProgramResult(); - if (result.getException() != null) { + if (!isEstimating && result.getException() != null + || result.getException() instanceof Program.OutOfTimeException) { RuntimeException e = result.getException(); - logger.warn("Constant call has an error {}", e.getMessage()); + logger.warn("Constant call failed for reason: {}", e.getMessage()); throw e; } @@ -3048,9 +3079,9 @@ public SmartContract getContract(GrpcAPI.BytesMessage bytesMessage) { byte[] address = bytesMessage.getValue().toByteArray(); AccountCapsule accountCapsule = chainBaseManager.getAccountStore().get(address); if (accountCapsule == null) { - logger.error( - "Get contract failed, the account does not exist or the account " - + "does not have a code hash!"); + logger.warn( + "Get contract failed, the account {} does not exist or the account " + + "does not have a code hash!", StringUtil.encode58Check(address)); return null; } @@ -3077,9 +3108,9 @@ public SmartContractDataWrapper getContractInfo(GrpcAPI.BytesMessage bytesMessag byte[] address = bytesMessage.getValue().toByteArray(); AccountCapsule accountCapsule = chainBaseManager.getAccountStore().get(address); if (accountCapsule == null) { - logger.error( - "Get contract failed, the account does not exist or the account does not have a code " - + "hash!"); + logger.warn( + "Get contract failed, the account {} does not exist or the account does not have a code " + + "hash!", StringUtil.encode58Check(address)); return null; } @@ -3851,7 +3882,7 @@ private boolean isShieldedTRC20NoteSpent(GrpcAPI.Note note, long pos, byte[] ak, retBuilder.setResult(false).setCode(response_code.CONTRACT_EXE_ERROR) .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); trxExtBuilder.setResult(retBuilder); - logger.warn("When run constant call in VM, have RuntimeException: " + e.getMessage()); + logger.warn("When run constant call in VM, failed for reason: " + e.getMessage()); } catch (Exception e) { retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); @@ -4115,7 +4146,7 @@ private byte[] getShieldedContractScalingFactor(byte[] contractAddress) retBuilder.setResult(false).setCode(response_code.CONTRACT_EXE_ERROR) .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); trxExtBuilder.setResult(retBuilder); - logger.warn("When run constant call in VM, have RuntimeException: " + e.getMessage()); + logger.warn("When run constant call in VM, failed for reason: " + e.getMessage()); } catch (Exception e) { retBuilder.setResult(false).setCode(response_code.OTHER_ERROR) .setMessage(ByteString.copyFromUtf8(e.getClass() + " : " + e.getMessage())); diff --git a/framework/src/main/java/org/tron/core/capsule/utils/RLP.java b/framework/src/main/java/org/tron/core/capsule/utils/RLP.java index 54e7d044346..60a84cfd3d3 100644 --- a/framework/src/main/java/org/tron/core/capsule/utils/RLP.java +++ b/framework/src/main/java/org/tron/core/capsule/utils/RLP.java @@ -204,7 +204,7 @@ public static long decodeLong(byte[] data, int index) { return value; } - private static String decodeStringItem(byte[] data, int index) { + public static String decodeStringItem(byte[] data, int index) { final byte[] valueBytes = decodeItemBytes(data, index); @@ -229,12 +229,12 @@ public static BigInteger decodeBigInteger(byte[] data, int index) { } } - private static byte[] decodeByteArray(byte[] data, int index) { + public static byte[] decodeByteArray(byte[] data, int index) { return decodeItemBytes(data, index); } - private static int nextItemLength(byte[] data, int index) { + public static int nextItemLength(byte[] data, int index) { if (index >= data.length) { return -1; diff --git a/framework/src/main/java/org/tron/core/config/args/Args.java b/framework/src/main/java/org/tron/core/config/args/Args.java index 8e6a7526362..50e4dacf6a9 100644 --- a/framework/src/main/java/org/tron/core/config/args/Args.java +++ b/framework/src/main/java/org/tron/core/config/args/Args.java @@ -24,7 +24,6 @@ import java.net.InetSocketAddress; import java.net.Socket; import java.net.URL; -import java.nio.file.Paths; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; @@ -64,9 +63,7 @@ import org.tron.common.setting.RocksDbSettings; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.LocalWitnesses; -import org.tron.common.utils.PropUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.config.Configuration; @@ -76,6 +73,9 @@ import org.tron.core.store.AccountStore; import org.tron.keystore.Credentials; import org.tron.keystore.WalletUtils; +import org.tron.p2p.dns.update.DnsType; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.utils.NetUtil; import org.tron.program.Version; @Slf4j(topic = "app") @@ -124,6 +124,7 @@ public static void clearParam() { PARAMETER.needSyncCheck = false; PARAMETER.nodeDiscoveryEnable = false; PARAMETER.nodeDiscoveryPersist = false; + PARAMETER.nodeEffectiveCheckEnable = false; PARAMETER.nodeConnectionTimeout = 2000; PARAMETER.activeNodes = new ArrayList<>(); PARAMETER.passiveNodes = new ArrayList<>(); @@ -134,6 +135,7 @@ public static void clearParam() { PARAMETER.minConnections = 8; PARAMETER.minActiveConnections = 3; PARAMETER.maxConnectionsWithSameIp = 2; + PARAMETER.maxTps = 1000; PARAMETER.minParticipationRate = 0; PARAMETER.nodeListenPort = 0; PARAMETER.nodeDiscoveryBindIp = ""; @@ -142,6 +144,10 @@ public static void clearParam() { PARAMETER.nodeDiscoveryPingTimeout = 15000; PARAMETER.nodeP2pPingInterval = 0L; PARAMETER.nodeP2pVersion = 0; + PARAMETER.nodeEnableIpv6 = false; + PARAMETER.dnsTreeUrls = new ArrayList<>(); + PARAMETER.dnsPublishConfig = null; + PARAMETER.syncFetchBatchNum = 2000; PARAMETER.rpcPort = 0; PARAMETER.rpcOnSolidityPort = 0; PARAMETER.rpcOnPBFTPort = 0; @@ -172,6 +178,7 @@ public static void clearParam() { PARAMETER.estimateEnergyMaxRetry = 3; PARAMETER.receiveTcpMinDataLength = 2048; PARAMETER.isOpenFullTcpDisconnect = false; + PARAMETER.nodeDetectEnable = false; PARAMETER.supportConstant = false; PARAMETER.debug = false; PARAMETER.minTimeRatio = 0.0; @@ -221,6 +228,12 @@ public static void clearParam() { PARAMETER.allowNewRewardAlgorithm = 0; PARAMETER.allowNewReward = 0; PARAMETER.memoFee = 0; + PARAMETER.rateLimiterGlobalQps = 50000; + PARAMETER.rateLimiterGlobalIpQps = 10000; + PARAMETER.p2pDisable = false; + PARAMETER.dynamicConfigEnable = false; + PARAMETER.dynamicConfigCheckInterval = 600; + PARAMETER.allowTvmShangHai = 0; } /** @@ -519,9 +532,7 @@ public static void setParam(final String[] args, final String confFileName) { PARAMETER.storage.setCacheStrategies(config); PARAMETER.seedNode = new SeedNode(); - PARAMETER.seedNode.setIpList(Optional.ofNullable(PARAMETER.seedNodes) - .filter(seedNode -> 0 != seedNode.size()) - .orElse(config.getStringList(Constant.SEED_NODE_IP_LIST))); + PARAMETER.seedNode.setAddressList(loadSeeds(config)); if (config.hasPath(Constant.GENESIS_BLOCK)) { PARAMETER.genesisBlock = new GenesisBlock(); @@ -552,13 +563,17 @@ public static void setParam(final String[] args, final String confFileName) { config.hasPath(Constant.NODE_DISCOVERY_PERSIST) && config.getBoolean(Constant.NODE_DISCOVERY_PERSIST); + PARAMETER.nodeEffectiveCheckEnable = + config.hasPath(Constant.NODE_EFFECTIVE_CHECK_ENABLE) + && config.getBoolean(Constant.NODE_EFFECTIVE_CHECK_ENABLE); + PARAMETER.nodeConnectionTimeout = config.hasPath(Constant.NODE_CONNECTION_TIMEOUT) ? config.getInt(Constant.NODE_CONNECTION_TIMEOUT) * 1000 : 2000; if (!config.hasPath(Constant.NODE_FETCH_BLOCK_TIMEOUT)) { - PARAMETER.fetchBlockTimeout = 200; + PARAMETER.fetchBlockTimeout = 500; } else if (config.getInt(Constant.NODE_FETCH_BLOCK_TIMEOUT) > 1000) { PARAMETER.fetchBlockTimeout = 1000; } else if (config.getInt(Constant.NODE_FETCH_BLOCK_TIMEOUT) < 100) { @@ -609,6 +624,9 @@ public static void setParam(final String[] args, final String confFileName) { .getInt(Constant.NODE_MAX_CONNECTIONS_WITH_SAME_IP) : 2; } + PARAMETER.maxTps = config.hasPath(Constant.NODE_MAX_TPS) + ? config.getInt(Constant.NODE_MAX_TPS) : 1000; + PARAMETER.minParticipationRate = config.hasPath(Constant.NODE_MIN_PARTICIPATION_RATE) ? config.getInt(Constant.NODE_MIN_PARTICIPATION_RATE) @@ -637,6 +655,23 @@ public static void setParam(final String[] args, final String confFileName) { config.hasPath(Constant.NODE_P2P_VERSION) ? config.getInt(Constant.NODE_P2P_VERSION) : 0; + PARAMETER.nodeEnableIpv6 = + config.hasPath(Constant.NODE_ENABLE_IPV6) && config.getBoolean(Constant.NODE_ENABLE_IPV6); + + PARAMETER.dnsTreeUrls = config.hasPath(Constant.NODE_DNS_TREE_URLS) ? config.getStringList( + Constant.NODE_DNS_TREE_URLS) : new ArrayList<>(); + + PARAMETER.dnsPublishConfig = loadDnsPublishConfig(config); + + PARAMETER.syncFetchBatchNum = config.hasPath(Constant.NODE_SYNC_FETCH_BATCH_NUM) ? config + .getInt(Constant.NODE_SYNC_FETCH_BATCH_NUM) : 2000; + if (PARAMETER.syncFetchBatchNum > 2000) { + PARAMETER.syncFetchBatchNum = 2000; + } + if (PARAMETER.syncFetchBatchNum < 100) { + PARAMETER.syncFetchBatchNum = 100; + } + PARAMETER.rpcPort = config.hasPath(Constant.NODE_RPC_PORT) ? config.getInt(Constant.NODE_RPC_PORT) : 50051; @@ -808,8 +843,13 @@ public static void setParam(final String[] args, final String confFileName) { PARAMETER.receiveTcpMinDataLength = config.hasPath(Constant.NODE_RECEIVE_TCP_MIN_DATA_LENGTH) ? config.getLong(Constant.NODE_RECEIVE_TCP_MIN_DATA_LENGTH) : 2048; + PARAMETER.isOpenFullTcpDisconnect = config.hasPath(Constant.NODE_IS_OPEN_FULL_TCP_DISCONNECT) && config.getBoolean(Constant.NODE_IS_OPEN_FULL_TCP_DISCONNECT); + + PARAMETER.nodeDetectEnable = config.hasPath(Constant.NODE_DETECT_ENABLE) + && config.getBoolean(Constant.NODE_DETECT_ENABLE); + PARAMETER.maxTransactionPendingSize = config.hasPath(Constant.NODE_MAX_TRANSACTION_PENDING_SIZE) ? config.getInt(Constant.NODE_MAX_TRANSACTION_PENDING_SIZE) : 2000; @@ -860,7 +900,6 @@ public static void setParam(final String[] args, final String confFileName) { config.hasPath(Constant.COMMITTEE_ALLOW_MARKET_TRANSACTION) ? config .getInt(Constant.COMMITTEE_ALLOW_MARKET_TRANSACTION) : 0; - PARAMETER.allowTransactionFeePool = config.hasPath(Constant.COMMITTEE_ALLOW_TRANSACTION_FEE_POOL) ? config .getInt(Constant.COMMITTEE_ALLOW_TRANSACTION_FEE_POOL) : 0; @@ -904,11 +943,11 @@ public static void setParam(final String[] args, final String confFileName) { .getInt(Constant.NODE_VALID_CONTRACT_PROTO_THREADS) : Runtime.getRuntime().availableProcessors(); - PARAMETER.activeNodes = getInetSocketAddress(config, Constant.NODE_ACTIVE); + PARAMETER.activeNodes = getInetSocketAddress(config, Constant.NODE_ACTIVE, true); PARAMETER.passiveNodes = getInetAddress(config, Constant.NODE_PASSIVE); - PARAMETER.fastForwardNodes = getInetSocketAddress(config, Constant.NODE_FAST_FORWARD); + PARAMETER.fastForwardNodes = getInetSocketAddress(config, Constant.NODE_FAST_FORWARD, true); PARAMETER.maxFastForwardNum = config.hasPath(Constant.NODE_MAX_FAST_FORWARD_NUM) ? config .getInt(Constant.NODE_MAX_FAST_FORWARD_NUM) : 3; @@ -927,9 +966,15 @@ public static void setParam(final String[] args, final String confFileName) { PARAMETER.fullNodeAllowShieldedTransactionArgs = true; } - PARAMETER.rateLimiterInitialization = - config.hasPath(Constant.RATE_LIMITER) ? getRateLimiterFromConfig(config) - : new RateLimiterInitialization(); + PARAMETER.rateLimiterGlobalQps = + config.hasPath(Constant.RATE_LIMITER_GLOBAL_QPS) ? config + .getInt(Constant.RATE_LIMITER_GLOBAL_QPS) : 50000; + + PARAMETER.rateLimiterGlobalIpQps = + config.hasPath(Constant.RATE_LIMITER_GLOBAL_IP_QPS) ? config + .getInt(Constant.RATE_LIMITER_GLOBAL_IP_QPS) : 10000; + + PARAMETER.rateLimiterInitialization = getRateLimiterFromConfig(config); PARAMETER.changedDelegation = config.hasPath(Constant.COMMITTEE_CHANGED_DELEGATION) ? config @@ -1122,6 +1167,22 @@ public static void setParam(final String[] args, final String confFileName) { Math.max(PARAMETER.dynamicEnergyMaxFactor, 0); } + PARAMETER.dynamicConfigEnable = config.hasPath(Constant.DYNAMIC_CONFIG_ENABLE) + && config.getBoolean(Constant.DYNAMIC_CONFIG_ENABLE); + if (config.hasPath(Constant.DYNAMIC_CONFIG_CHECK_INTERVAL)) { + PARAMETER.dynamicConfigCheckInterval + = config.getLong(Constant.DYNAMIC_CONFIG_CHECK_INTERVAL); + if (PARAMETER.dynamicConfigCheckInterval <= 0) { + PARAMETER.dynamicConfigCheckInterval = 600; + } + } else { + PARAMETER.dynamicConfigCheckInterval = 600; + } + + PARAMETER.allowTvmShangHai = + config.hasPath(Constant.COMMITTEE_ALLOW_TVM_SHANGHAI) ? config + .getInt(Constant.COMMITTEE_ALLOW_TVM_SHANGHAI) : 0; + logConfig(); } @@ -1156,58 +1217,60 @@ private static Account createAccount(final ConfigObject asset) { } private static RateLimiterInitialization getRateLimiterFromConfig( - final com.typesafe.config.Config config) { - + final com.typesafe.config.Config config) { RateLimiterInitialization initialization = new RateLimiterInitialization(); - ArrayList list1 = config - .getObjectList(Constant.RATE_LIMITER_HTTP).stream() - .map(RateLimiterInitialization::createHttpItem) - .collect(Collectors.toCollection(ArrayList::new)); - initialization.setHttpMap(list1); - - ArrayList list2 = config - .getObjectList(Constant.RATE_LIMITER_RPC).stream() - .map(RateLimiterInitialization::createRpcItem) - .collect(Collectors.toCollection(ArrayList::new)); - - initialization.setRpcMap(list2); + if (config.hasPath(Constant.RATE_LIMITER_HTTP)) { + ArrayList list1 = config + .getObjectList(Constant.RATE_LIMITER_HTTP).stream() + .map(RateLimiterInitialization::createHttpItem) + .collect(Collectors.toCollection(ArrayList::new)); + initialization.setHttpMap(list1); + } + if (config.hasPath(Constant.RATE_LIMITER_RPC)) { + ArrayList list2 = config + .getObjectList(Constant.RATE_LIMITER_RPC).stream() + .map(RateLimiterInitialization::createRpcItem) + .collect(Collectors.toCollection(ArrayList::new)); + initialization.setRpcMap(list2); + } return initialization; } - private static List getInetSocketAddress( - final com.typesafe.config.Config config, String path) { + public static List getInetSocketAddress( + final com.typesafe.config.Config config, String path, boolean filter) { List ret = new ArrayList<>(); if (!config.hasPath(path)) { return ret; } List list = config.getStringList(path); for (String configString : list) { - String[] sz = configString.split(":"); - String ip = sz[0]; - int port = Integer.parseInt(sz[1]); - if (!(PARAMETER.nodeDiscoveryBindIp.equals(ip) - || PARAMETER.nodeExternalIp.equals(ip) - || Constant.LOCAL_HOST.equals(ip)) - || PARAMETER.nodeListenPort != port) { - ret.add(new InetSocketAddress(ip, port)); + InetSocketAddress inetSocketAddress = NetUtil.parseInetSocketAddress(configString); + if (filter) { + String ip = inetSocketAddress.getAddress().getHostAddress(); + int port = inetSocketAddress.getPort(); + if (!(PARAMETER.nodeDiscoveryBindIp.equals(ip) + || PARAMETER.nodeExternalIp.equals(ip) + || Constant.LOCAL_HOST.equals(ip)) + || PARAMETER.nodeListenPort != port) { + ret.add(inetSocketAddress); + } + } else { + ret.add(inetSocketAddress); } } return ret; } - private static List getInetAddress( - final com.typesafe.config.Config config, String path) { + public static List getInetAddress( + final com.typesafe.config.Config config, String path) { List ret = new ArrayList<>(); if (!config.hasPath(path)) { return ret; } List list = config.getStringList(path); for (String configString : list) { - try { - ret.add(InetAddress.getByName(configString.split(":")[0])); - } catch (Exception e) { - logger.warn("Get inet address failed, {}", e.getMessage()); - } + InetSocketAddress inetSocketAddress = NetUtil.parseInetSocketAddress(configString); + ret.add(inetSocketAddress.getAddress()); } return ret; } @@ -1271,6 +1334,128 @@ private static EventPluginConfig getEventPluginConfig( return eventPluginConfig; } + private static List loadSeeds(final com.typesafe.config.Config config) { + List inetSocketAddressList = new ArrayList<>(); + if (PARAMETER.seedNodes != null && !PARAMETER.seedNodes.isEmpty()) { + for (String s : PARAMETER.seedNodes) { + InetSocketAddress inetSocketAddress = NetUtil.parseInetSocketAddress(s); + inetSocketAddressList.add(inetSocketAddress); + } + } else { + inetSocketAddressList = getInetSocketAddress(config, Constant.SEED_NODE_IP_LIST, false); + } + + return inetSocketAddressList; + } + + public static PublishConfig loadDnsPublishConfig(final com.typesafe.config.Config config) { + PublishConfig publishConfig = new PublishConfig(); + if (config.hasPath(Constant.NODE_DNS_PUBLISH)) { + publishConfig.setDnsPublishEnable(config.getBoolean(Constant.NODE_DNS_PUBLISH)); + } + loadDnsPublishParameters(config, publishConfig); + return publishConfig; + } + + public static void loadDnsPublishParameters(final com.typesafe.config.Config config, + PublishConfig publishConfig) { + if (publishConfig.isDnsPublishEnable()) { + if (config.hasPath(Constant.NODE_DNS_DOMAIN) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_DOMAIN))) { + publishConfig.setDnsDomain(config.getString(Constant.NODE_DNS_DOMAIN)); + } else { + logEmptyError(Constant.NODE_DNS_DOMAIN); + } + + if (config.hasPath(Constant.NODE_DNS_CHANGE_THRESHOLD)) { + double changeThreshold = config.getDouble(Constant.NODE_DNS_CHANGE_THRESHOLD); + if (changeThreshold > 0) { + publishConfig.setChangeThreshold(changeThreshold); + } else { + logger.error("Check {}, should be bigger than 0, default 0.1", + Constant.NODE_DNS_CHANGE_THRESHOLD); + } + } + + if (config.hasPath(Constant.NODE_DNS_MAX_MERGE_SIZE)) { + int maxMergeSize = config.getInt(Constant.NODE_DNS_MAX_MERGE_SIZE); + if (maxMergeSize >= 1 && maxMergeSize <= 5) { + publishConfig.setMaxMergeSize(maxMergeSize); + } else { + logger.error("Check {}, should be [1~5], default 5", Constant.NODE_DNS_MAX_MERGE_SIZE); + } + } + + if (config.hasPath(Constant.NODE_DNS_PRIVATE) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_PRIVATE))) { + publishConfig.setDnsPrivate(config.getString(Constant.NODE_DNS_PRIVATE)); + } else { + logEmptyError(Constant.NODE_DNS_PRIVATE); + } + + if (config.hasPath(Constant.NODE_DNS_KNOWN_URLS)) { + publishConfig.setKnownTreeUrls(config.getStringList(Constant.NODE_DNS_KNOWN_URLS)); + } + + if (config.hasPath(Constant.NODE_DNS_STATIC_NODES)) { + publishConfig.setStaticNodes( + getInetSocketAddress(config, Constant.NODE_DNS_STATIC_NODES, false)); + } + + if (config.hasPath(Constant.NODE_DNS_SERVER_TYPE) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_SERVER_TYPE))) { + String serverType = config.getString(Constant.NODE_DNS_SERVER_TYPE); + if (!"aws".equalsIgnoreCase(serverType) && !"aliyun".equalsIgnoreCase(serverType)) { + throw new IllegalArgumentException( + String.format("Check %s, must be aws or aliyun", Constant.NODE_DNS_SERVER_TYPE)); + } + if ("aws".equalsIgnoreCase(serverType)) { + publishConfig.setDnsType(DnsType.AwsRoute53); + } else { + publishConfig.setDnsType(DnsType.AliYun); + } + } else { + logEmptyError(Constant.NODE_DNS_SERVER_TYPE); + } + + if (config.hasPath(Constant.NODE_DNS_ACCESS_KEY_ID) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_ACCESS_KEY_ID))) { + publishConfig.setAccessKeyId(config.getString(Constant.NODE_DNS_ACCESS_KEY_ID)); + } else { + logEmptyError(Constant.NODE_DNS_ACCESS_KEY_ID); + } + if (config.hasPath(Constant.NODE_DNS_ACCESS_KEY_SECRET) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_ACCESS_KEY_SECRET))) { + publishConfig.setAccessKeySecret(config.getString(Constant.NODE_DNS_ACCESS_KEY_SECRET)); + } else { + logEmptyError(Constant.NODE_DNS_ACCESS_KEY_SECRET); + } + + if (publishConfig.getDnsType() == DnsType.AwsRoute53) { + if (config.hasPath(Constant.NODE_DNS_AWS_REGION) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_AWS_REGION))) { + publishConfig.setAwsRegion(config.getString(Constant.NODE_DNS_AWS_REGION)); + } else { + logEmptyError(Constant.NODE_DNS_AWS_REGION); + } + if (config.hasPath(Constant.NODE_DNS_AWS_HOST_ZONE_ID)) { + publishConfig.setAwsHostZoneId(config.getString(Constant.NODE_DNS_AWS_HOST_ZONE_ID)); + } + } else { + if (config.hasPath(Constant.NODE_DNS_ALIYUN_ENDPOINT) && StringUtils.isNotEmpty( + config.getString(Constant.NODE_DNS_ALIYUN_ENDPOINT))) { + publishConfig.setAliDnsEndpoint(config.getString(Constant.NODE_DNS_ALIYUN_ENDPOINT)); + } else { + logEmptyError(Constant.NODE_DNS_ALIYUN_ENDPOINT); + } + } + } + } + + private static void logEmptyError(String arg) { + throw new IllegalArgumentException(String.format("Check %s, must not be null or empty", arg)); + } + private static TriggerConfig createTriggerConfig(ConfigObject triggerObject) { if (Objects.isNull(triggerObject)) { return null; @@ -1467,18 +1652,24 @@ public static void logConfig() { logger.info("Bind IP: {}", parameter.getNodeDiscoveryBindIp()); logger.info("External IP: {}", parameter.getNodeExternalIp()); logger.info("Listen port: {}", parameter.getNodeListenPort()); + logger.info("Node ipv6 enable: {}", parameter.isNodeEnableIpv6()); logger.info("Discover enable: {}", parameter.isNodeDiscoveryEnable()); logger.info("Active node size: {}", parameter.getActiveNodes().size()); logger.info("Passive node size: {}", parameter.getPassiveNodes().size()); logger.info("FastForward node size: {}", parameter.getFastForwardNodes().size()); logger.info("FastForward node number: {}", parameter.getMaxFastForwardNum()); - logger.info("Seed node size: {}", parameter.getSeedNode().getIpList().size()); + logger.info("Seed node size: {}", parameter.getSeedNode().getAddressList().size()); logger.info("Max connection: {}", parameter.getMaxConnections()); logger.info("Min connection: {}", parameter.getMinConnections()); logger.info("Min active connection: {}", parameter.getMinActiveConnections()); logger.info("Max connection with same IP: {}", parameter.getMaxConnectionsWithSameIp()); logger.info("Solidity threads: {}", parameter.getSolidityThreads()); logger.info("Trx reference block: {}", parameter.getTrxReferenceBlock()); + logger.info("Open full tcp disconnect: {}", parameter.isOpenFullTcpDisconnect()); + logger.info("Node detect enable: {}", parameter.isNodeDetectEnable()); + logger.info("Node effective check enable: {}", parameter.isNodeEffectiveCheckEnable()); + logger.info("Rate limiter global qps: {}", parameter.getRateLimiterGlobalQps()); + logger.info("Rate limiter global ip qps: {}", parameter.getRateLimiterGlobalIpQps()); logger.info("************************ Backup config ************************"); logger.info("Backup priority: {}", parameter.getBackupPriority()); logger.info("Backup listen port: {}", parameter.getBackupPort()); diff --git a/framework/src/main/java/org/tron/core/config/args/DynamicArgs.java b/framework/src/main/java/org/tron/core/config/args/DynamicArgs.java new file mode 100644 index 00000000000..cbf167cb955 --- /dev/null +++ b/framework/src/main/java/org/tron/core/config/args/DynamicArgs.java @@ -0,0 +1,114 @@ +package org.tron.core.config.args; + +import static org.apache.commons.lang3.StringUtils.isNoneBlank; + +import com.typesafe.config.Config; +import java.io.File; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.Constant; +import org.tron.core.config.Configuration; +import org.tron.core.net.TronNetService; + + +@Slf4j(topic = "app") +@Component +public class DynamicArgs { + private final CommonParameter parameter = Args.getInstance(); + + private long lastModified = 0; + + private ScheduledExecutorService reloadExecutor = Executors.newSingleThreadScheduledExecutor(); + + public void init() { + if (parameter.isDynamicConfigEnable()) { + logger.info("Start the dynamic loading configuration service"); + long checkInterval = parameter.getDynamicConfigCheckInterval(); + File config = getConfigFile(); + if (config == null) { + return; + } + lastModified = config.lastModified(); + reloadExecutor.scheduleWithFixedDelay(() -> { + try { + run(); + } catch (Exception e) { + logger.error("Exception caught when reloading configuration", e); + } + }, 10, checkInterval, TimeUnit.SECONDS); + } + } + + public void run() { + File config = getConfigFile(); + if (config != null) { + long lastModifiedTime = config.lastModified(); + if (lastModifiedTime > lastModified) { + reload(); + lastModified = lastModifiedTime; + } + } + } + + private File getConfigFile() { + String confFilePath; + if (isNoneBlank(parameter.getShellConfFileName())) { + confFilePath = parameter.getShellConfFileName(); + } else { + confFilePath = Constant.TESTNET_CONF; + } + + File confFile = new File(confFilePath); + if (!confFile.exists()) { + logger.warn("Configuration path is required! No such file {}", confFile); + return null; + } + return confFile; + } + + public void reload() { + logger.debug("Reloading ... "); + Config config = Configuration.getByFileName(parameter.getShellConfFileName(), + Constant.TESTNET_CONF); + + updateActiveNodes(config); + + updateTrustNodes(config); + } + + private void updateActiveNodes(Config config) { + List newActiveNodes = + Args.getInetSocketAddress(config, Constant.NODE_ACTIVE, true); + parameter.setActiveNodes(newActiveNodes); + List activeNodes = TronNetService.getP2pConfig().getActiveNodes(); + activeNodes.clear(); + activeNodes.addAll(newActiveNodes); + logger.debug("p2p active nodes : {}", + TronNetService.getP2pConfig().getActiveNodes().toString()); + } + + private void updateTrustNodes(Config config) { + List newPassiveNodes = Args.getInetAddress(config, Constant.NODE_PASSIVE); + parameter.setPassiveNodes(newPassiveNodes); + List trustNodes = TronNetService.getP2pConfig().getTrustNodes(); + trustNodes.clear(); + trustNodes.addAll(newPassiveNodes); + parameter.getActiveNodes().forEach(n -> trustNodes.add(n.getAddress())); + parameter.getFastForwardNodes().forEach(f -> trustNodes.add(f.getAddress())); + logger.debug("p2p trust nodes : {}", + TronNetService.getP2pConfig().getTrustNodes().toString()); + } + + public void close() { + logger.info("Closing the dynamic loading configuration service"); + reloadExecutor.shutdown(); + } +} \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/consensus/ProposalService.java b/framework/src/main/java/org/tron/core/consensus/ProposalService.java index fb4c24eee40..2cbf0c053d6 100644 --- a/framework/src/main/java/org/tron/core/consensus/ProposalService.java +++ b/framework/src/main/java/org/tron/core/consensus/ProposalService.java @@ -339,6 +339,22 @@ public static boolean process(Manager manager, ProposalCapsule proposalCapsule) manager.getDynamicPropertiesStore().saveDynamicEnergyMaxFactor(entry.getValue()); break; } + case ALLOW_TVM_SHANGHAI: { + manager.getDynamicPropertiesStore().saveAllowTvmShangHai(entry.getValue()); + break; + } + case ALLOW_CANCEL_ALL_UNFREEZE_V2: { + if (manager.getDynamicPropertiesStore().getAllowCancelAllUnfreezeV2() == 0) { + manager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(entry.getValue()); + manager.getDynamicPropertiesStore().addSystemContractAndSetPermission( + ContractType.CancelAllUnfreezeV2Contract_VALUE); + } + break; + } + case MAX_DELEGATE_LOCK_PERIOD: { + manager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(entry.getValue()); + break; + } default: find = false; break; diff --git a/framework/src/main/java/org/tron/core/db/Manager.java b/framework/src/main/java/org/tron/core/db/Manager.java index 9e7c27029f5..3928f657e44 100644 --- a/framework/src/main/java/org/tron/core/db/Manager.java +++ b/framework/src/main/java/org/tron/core/db/Manager.java @@ -1,6 +1,7 @@ package org.tron.core.db; import static org.tron.common.utils.Commons.adjustBalance; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract; import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; @@ -192,7 +193,8 @@ public class Manager { @Getter @Setter private boolean isSyncMode; - + @Getter + private Object forkLock = new Object(); // map @Getter @Setter @@ -241,6 +243,8 @@ public class Manager { @Getter private volatile long latestSolidityNumShutDown; @Getter + private long lastUsedSolidityNum = -1; + @Getter private int maxFlushCount; @Getter @@ -446,6 +450,7 @@ public void init() { trieService.setChainBaseManager(chainBaseManager); revokingStore.disable(); revokingStore.check(); + transactionCache.initCache(); this.setProposalController(ProposalController.createInstance(this)); this.setMerkleContainer( merkleContainer.createInstance(chainBaseManager.getMerkleTreeStore(), @@ -717,7 +722,7 @@ private void initAutoStop() { exitCount, blockTime)); } - if (exitHeight == headNum) { + if (exitHeight == headNum && (!Args.getInstance().isP2pDisable())) { logger.info("Auto-stop hit: shutDownBlockHeight: {}, currentHeaderNum: {}, exit now", exitHeight, headNum); System.exit(0); @@ -1211,8 +1216,8 @@ public void pushBlock(final BlockCapsule block) if (!block.calcMerkleRoot().equals(block.getMerkleRoot())) { logger.warn("Num: {}, the merkle root doesn't match, expect is {} , actual is {}.", block.getNum(), block.getMerkleRoot(), block.calcMerkleRoot()); - throw new BadBlockException(String.format("The merkle hash is not validated for %d", - block.getNum())); + throw new BadBlockException(CALC_MERKLE_ROOT_FAILED, + String.format("The merkle hash is not validated for %d", block.getNum())); } consensus.receiveBlock(block); } @@ -1266,8 +1271,9 @@ public void pushBlock(final BlockCapsule block) chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(), khaosDb.getHead(), khaosDb.getMiniStore().size(), khaosDb.getMiniUnlinkedStore().size()); - - switchFork(newBlock); + synchronized (forkLock) { + switchFork(newBlock); + } logger.info(SAVE_BLOCK, newBlock); logger.warn( @@ -1607,7 +1613,7 @@ public BlockCapsule generateBlock(Miner miner, long blockTime, long timeout) { toBePacked.add(trx); currentSize += trxPackSize; } catch (Exception e) { - logger.error("Process trx {} failed when generating block {}, {}.", trx.getTransactionId(), + logger.warn("Process trx {} failed when generating block {}, {}.", trx.getTransactionId(), blockCapsule.getNum(), e.getMessage()); } } @@ -1741,16 +1747,20 @@ private void processBlock(BlockCapsule block, List txs) payReward(block); - if (chainBaseManager.getDynamicPropertiesStore().getNextMaintenanceTime() - <= block.getTimeStamp()) { + boolean flag = chainBaseManager.getDynamicPropertiesStore().getNextMaintenanceTime() + <= block.getTimeStamp(); + if (flag) { proposalController.processProposals(); - chainBaseManager.getForkController().reset(); } if (!consensus.applyBlock(block)) { throw new BadBlockException("consensus apply block failed"); } + if (flag) { + chainBaseManager.getForkController().reset(); + } + updateTransHashCache(block); updateRecentBlock(block); updateRecentTransaction(block); @@ -1910,6 +1920,7 @@ public NullifierStore getNullifierStore() { public void closeAllStore() { logger.info("******** Begin to close db. ********"); chainBaseManager.closeAllStore(); + validateSignService.shutdown(); logger.info("******** End to close db. ********"); } @@ -2030,17 +2041,11 @@ private void postSolidityFilter(final long oldSolidNum, final long latestSolidif return; } - BlockCapsule blockCapsule; - try { - blockCapsule = chainBaseManager.getBlockByNum(latestSolidifiedBlockNumber); - } catch (Exception e) { - logger.error("PostSolidityFilter getBlockByNum = {} except, {}.", - latestSolidifiedBlockNumber, e.getMessage()); - return; + List capsuleList = getContinuousBlockCapsule(latestSolidifiedBlockNumber); + for (BlockCapsule blockCapsule : capsuleList) { + postBlockFilter(blockCapsule, true); + postLogsFilter(blockCapsule, true, false); } - - postBlockFilter(blockCapsule, true); - postLogsFilter(blockCapsule, true, false); } private void postSolidityTrigger(final long oldSolidNum, final long latestSolidifiedBlockNumber) { @@ -2057,28 +2062,23 @@ private void postSolidityTrigger(final long oldSolidNum, final long latestSolidi } if (eventPluginLoaded && EventPluginLoader.getInstance().isSolidityTriggerEnable()) { - SolidityTriggerCapsule solidityTriggerCapsule - = new SolidityTriggerCapsule(latestSolidifiedBlockNumber); - - BlockCapsule blockCapsule; - try { - blockCapsule = chainBaseManager.getBlockByNum(latestSolidifiedBlockNumber); + List capsuleList = getContinuousBlockCapsule(latestSolidifiedBlockNumber); + for (BlockCapsule blockCapsule : capsuleList) { + SolidityTriggerCapsule solidityTriggerCapsule + = new SolidityTriggerCapsule(blockCapsule.getNum());//unique key solidityTriggerCapsule.setTimeStamp(blockCapsule.getTimeStamp()); - } catch (Exception e) { - logger.error("PostSolidityTrigger getBlockByNum = {} except, {}.", - latestSolidifiedBlockNumber, e.getMessage()); - } - - boolean result = triggerCapsuleQueue.offer(solidityTriggerCapsule); - if (!result) { - logger.info("Too many trigger, lost solidified trigger, block number: {}.", - latestSolidifiedBlockNumber); + boolean result = triggerCapsuleQueue.offer(solidityTriggerCapsule); + if (!result) { + logger.info("Too many trigger, lost solidified trigger, block number: {}.", + blockCapsule.getNum()); + } } } if (CommonParameter.getInstance().isJsonRpcHttpSolidityNodeEnable()) { postSolidityFilter(oldSolidNum, latestSolidifiedBlockNumber); } + lastUsedSolidityNum = latestSolidifiedBlockNumber; } private void processTransactionTrigger(BlockCapsule newBlock) { @@ -2189,8 +2189,6 @@ private void postLogsFilter(final BlockCapsule blockCapsule, boolean solidified, } private void postBlockTrigger(final BlockCapsule blockCapsule) { - BlockCapsule newBlock = blockCapsule; - // post block and logs for jsonrpc if (CommonParameter.getInstance().isJsonRpcHttpFullNodeEnable()) { postBlockFilter(blockCapsule, false); @@ -2198,44 +2196,56 @@ private void postBlockTrigger(final BlockCapsule blockCapsule) { } // process block trigger + long solidityBlkNum = getDynamicPropertiesStore().getLatestSolidifiedBlockNum(); if (eventPluginLoaded && EventPluginLoader.getInstance().isBlockLogTriggerEnable()) { + List capsuleList = new ArrayList<>(); if (EventPluginLoader.getInstance().isBlockLogTriggerSolidified()) { - long solidityBlkNum = getDynamicPropertiesStore().getLatestSolidifiedBlockNum(); - try { - newBlock = chainBaseManager - .getBlockByNum(solidityBlkNum); - } catch (Exception e) { - logger.error("PostBlockTrigger getBlockByNum blkNum = {} except, error is {}.", - solidityBlkNum, e.getMessage()); - } + capsuleList = getContinuousBlockCapsule(solidityBlkNum); + } else { + capsuleList.add(blockCapsule); } - BlockLogTriggerCapsule blockLogTriggerCapsule = new BlockLogTriggerCapsule(newBlock); - blockLogTriggerCapsule.setLatestSolidifiedBlockNumber(getDynamicPropertiesStore() - .getLatestSolidifiedBlockNum()); - if (!triggerCapsuleQueue.offer(blockLogTriggerCapsule)) { - logger.info("Too many triggers, block trigger lost: {}.", newBlock.getBlockId()); + for (BlockCapsule capsule : capsuleList) { + BlockLogTriggerCapsule blockLogTriggerCapsule = new BlockLogTriggerCapsule(capsule); + blockLogTriggerCapsule.setLatestSolidifiedBlockNumber(solidityBlkNum); + if (!triggerCapsuleQueue.offer(blockLogTriggerCapsule)) { + logger.info("Too many triggers, block trigger lost: {}.", capsule.getBlockId()); + } } } // process transaction trigger if (eventPluginLoaded && EventPluginLoader.getInstance().isTransactionLogTriggerEnable()) { - // set newBlock + List capsuleList = new ArrayList<>(); if (EventPluginLoader.getInstance().isTransactionLogTriggerSolidified()) { - long solidityBlkNum = getDynamicPropertiesStore().getLatestSolidifiedBlockNum(); - try { - newBlock = chainBaseManager.getBlockByNum(solidityBlkNum); - } catch (Exception e) { - logger.error("PostBlockTrigger getBlockByNum blkNum = {} except, error is {}.", - solidityBlkNum, e.getMessage()); - } + capsuleList = getContinuousBlockCapsule(solidityBlkNum); } else { // need to reset block - newBlock = blockCapsule; + capsuleList.add(blockCapsule); } - processTransactionTrigger(newBlock); + for (BlockCapsule capsule : capsuleList) { + processTransactionTrigger(capsule); + } + } + } + + private List getContinuousBlockCapsule(long solidityBlkNum) { + List capsuleList = new ArrayList<>(); + long start = lastUsedSolidityNum < 0 ? solidityBlkNum : (lastUsedSolidityNum + 1); + if (solidityBlkNum > start) { + logger.info("Continuous block start:{}, end:{}", start, solidityBlkNum); + } + for (long blockNum = start; blockNum <= solidityBlkNum; blockNum++) { + try { + BlockCapsule capsule = chainBaseManager.getBlockByNum(blockNum); + capsuleList.add(capsule); + } catch (Exception e) { + logger.error("GetContinuousBlockCapsule getBlockByNum blkNum = {} except, error is {}.", + solidityBlkNum, e.getMessage()); + } } + return capsuleList; } // return energyUsageTotal of the current transaction diff --git a/framework/src/main/java/org/tron/core/db/TransactionCache.java b/framework/src/main/java/org/tron/core/db/TransactionCache.java index 715d82185d0..70b42ca7226 100644 --- a/framework/src/main/java/org/tron/core/db/TransactionCache.java +++ b/framework/src/main/java/org/tron/core/db/TransactionCache.java @@ -14,4 +14,8 @@ public TransactionCache(@Value("trans-cache") String dbName, RecentTransactionStore recentTransactionStore) { super(new TxCacheDB(dbName, recentTransactionStore)); } + + public void initCache() { + ((TxCacheDB) getDb()).init(); + } } diff --git a/framework/src/main/java/org/tron/core/net/P2pEventHandlerImpl.java b/framework/src/main/java/org/tron/core/net/P2pEventHandlerImpl.java index 66774a216f2..10615b70ce3 100644 --- a/framework/src/main/java/org/tron/core/net/P2pEventHandlerImpl.java +++ b/framework/src/main/java/org/tron/core/net/P2pEventHandlerImpl.java @@ -1,5 +1,7 @@ package org.tron.core.net; +import static org.tron.core.net.message.MessageTypes.INVENTORY; + import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -11,11 +13,13 @@ import org.tron.common.prometheus.MetricKeys; import org.tron.common.prometheus.Metrics; import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.PbftMessageFactory; import org.tron.core.net.message.TronMessage; import org.tron.core.net.message.TronMessageFactory; +import org.tron.core.net.message.adv.InventoryMessage; import org.tron.core.net.message.base.DisconnectMessage; import org.tron.core.net.message.handshake.HelloMessage; import org.tron.core.net.messagehandler.BlockMsgHandler; @@ -28,6 +32,7 @@ import org.tron.core.net.messagehandler.TransactionsMsgHandler; import org.tron.core.net.peer.PeerConnection; import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.service.effective.EffectiveCheckService; import org.tron.core.net.service.handshake.HandshakeService; import org.tron.core.net.service.keepalive.KeepAliveService; import org.tron.p2p.P2pEventHandler; @@ -78,8 +83,13 @@ public class P2pEventHandlerImpl extends P2pEventHandler { @Autowired private KeepAliveService keepAliveService; + @Autowired + private EffectiveCheckService effectiveCheckService; + private byte MESSAGE_MAX_TYPE = 127; + private int maxCountIn10s = Args.getInstance().getMaxTps() * 10; + public P2pEventHandlerImpl() { Set set = new HashSet<>(); for (byte i = 0; i < MESSAGE_MAX_TYPE; i++) { @@ -102,6 +112,7 @@ public synchronized void onDisconnect(Channel channel) { if (peerConnection != null) { peerConnection.onDisconnect(); } + effectiveCheckService.onDisconnect(channel.getInetSocketAddress()); } @Override @@ -135,10 +146,27 @@ private void processMessage(PeerConnection peer, byte[] data) { try { msg = TronMessageFactory.create(data); type = msg.getType(); + + if (INVENTORY.equals(type)) { + InventoryMessage message = (InventoryMessage) msg; + Protocol.Inventory.InventoryType inventoryType = message.getInventoryType(); + int count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement + .getCount(10); + if (inventoryType.equals(Protocol.Inventory.InventoryType.TRX) && count > maxCountIn10s) { + logger.warn("Drop inventory from Peer {}, cur:{}, max:{}", + peer.getInetAddress(), count, maxCountIn10s); + if (Args.getInstance().isOpenPrintLog()) { + logger.warn("[overload]Drop tx list is: {}", ((InventoryMessage) msg).getHashList()); + } + return; + } + } + peer.getPeerStatistics().messageStatistics.addTcpInMessage(msg); if (PeerConnection.needToLog(msg)) { logger.info("Receive message from peer: {}, {}", peer.getInetSocketAddress(), msg); } + switch (type) { case P2P_PING: case P2P_PONG: diff --git a/framework/src/main/java/org/tron/core/net/TronNetDelegate.java b/framework/src/main/java/org/tron/core/net/TronNetDelegate.java index 05dde7a9701..4d22f98d680 100644 --- a/framework/src/main/java/org/tron/core/net/TronNetDelegate.java +++ b/framework/src/main/java/org/tron/core/net/TronNetDelegate.java @@ -1,6 +1,7 @@ package org.tron.core.net; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; @@ -145,6 +146,10 @@ public BlockId getHeadBlockId() { return chainBaseManager.getHeadBlockId(); } + public BlockId getKhaosDbHeadBlockId() { + return chainBaseManager.getKhaosDbHead().getBlockId(); + } + public BlockId getSolidBlockId() { return chainBaseManager.getSolidBlockId(); } @@ -282,7 +287,12 @@ public void processBlock(BlockCapsule block, boolean isSync) throws P2pException | EventBloomException e) { metricsService.failProcessBlock(block.getNum(), e.getMessage()); logger.error("Process block failed, {}, reason: {}", blockId.getString(), e.getMessage()); - throw new P2pException(TypeEnum.BAD_BLOCK, e); + if (e instanceof BadBlockException + && ((BadBlockException) e).getType().equals(CALC_MERKLE_ROOT_FAILED)) { + throw new P2pException(TypeEnum.BLOCK_MERKLE_ERROR, e); + } else { + throw new P2pException(TypeEnum.BAD_BLOCK, e); + } } } } @@ -309,13 +319,15 @@ public void pushTransaction(TransactionCapsule trx) throws P2pException { } public void validSignature(BlockCapsule block) throws P2pException { + boolean flag; try { - if (!block.validateSignature(dbManager.getDynamicPropertiesStore(), - dbManager.getAccountStore())) { - throw new P2pException(TypeEnum.BAD_BLOCK, "valid signature failed."); - } - } catch (ValidateSignatureException e) { - throw new P2pException(TypeEnum.BAD_BLOCK, e); + flag = block.validateSignature(dbManager.getDynamicPropertiesStore(), + dbManager.getAccountStore()); + } catch (Exception e) { + throw new P2pException(TypeEnum.BLOCK_SIGN_ERROR, e); + } + if (!flag) { + throw new P2pException(TypeEnum.BLOCK_SIGN_ERROR, "valid signature failed."); } } @@ -341,4 +353,8 @@ public boolean allowPBFT() { return chainBaseManager.getDynamicPropertiesStore().allowPBFT(); } + public Object getForkLock() { + return dbManager.getForkLock(); + } + } diff --git a/framework/src/main/java/org/tron/core/net/TronNetService.java b/framework/src/main/java/org/tron/core/net/TronNetService.java index dcee7ecc7b2..87d878be8c9 100644 --- a/framework/src/main/java/org/tron/core/net/TronNetService.java +++ b/framework/src/main/java/org/tron/core/net/TronNetService.java @@ -1,11 +1,15 @@ package org.tron.core.net; -import io.netty.util.internal.StringUtil; +import java.net.Inet4Address; +import java.net.InetAddress; import java.net.InetSocketAddress; -import java.util.ArrayList; +import java.net.UnknownHostException; import java.util.List; +import java.util.Objects; +import java.util.Set; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.tron.common.overlay.message.Message; @@ -17,14 +21,15 @@ import org.tron.core.net.peer.PeerManager; import org.tron.core.net.peer.PeerStatusCheck; import org.tron.core.net.service.adv.AdvService; +import org.tron.core.net.service.effective.EffectiveCheckService; import org.tron.core.net.service.fetchblock.FetchBlockService; -import org.tron.core.net.service.keepalive.KeepAliveService; import org.tron.core.net.service.nodepersist.NodePersistService; import org.tron.core.net.service.relay.RelayService; import org.tron.core.net.service.statistics.TronStatsManager; import org.tron.core.net.service.sync.SyncService; import org.tron.p2p.P2pConfig; import org.tron.p2p.P2pService; +import org.tron.p2p.utils.NetUtil; @Slf4j(topic = "net") @Component @@ -51,9 +56,6 @@ public class TronNetService { @Autowired private FetchBlockService fetchBlockService; - @Autowired - private KeepAliveService keepAliveService; - private CommonParameter parameter = Args.getInstance(); @Autowired @@ -68,12 +70,15 @@ public class TronNetService { @Autowired private RelayService relayService; + @Autowired + private EffectiveCheckService effectiveCheckService; + private volatile boolean init; private static void setP2pConfig(P2pConfig config) { TronNetService.p2pConfig = config; } - + public void start() { try { init = true; @@ -85,11 +90,11 @@ public void start() { peerStatusCheck.init(); transactionsMsgHandler.init(); fetchBlockService.init(); - keepAliveService.init(); nodePersistService.init(); tronStatsManager.init(); PeerManager.init(); relayService.init(); + effectiveCheckService.init(); logger.info("Net service start successfully"); } catch (Exception e) { logger.error("Net service start failed", e); @@ -103,12 +108,12 @@ public void close() { PeerManager.close(); tronStatsManager.close(); nodePersistService.close(); - keepAliveService.close(); advService.close(); syncService.close(); peerStatusCheck.close(); transactionsMsgHandler.close(); fetchBlockService.close(); + effectiveCheckService.close(); p2pService.close(); relayService.close(); logger.info("Net service closed successfully"); @@ -126,18 +131,34 @@ public int fastBroadcastTransaction(TransactionMessage msg) { return advService.fastBroadcastTransaction(msg); } - private P2pConfig getConfig() { - List seeds = new ArrayList<>(); - seeds.addAll(nodePersistService.dbRead()); - for (String s : parameter.getSeedNode().getIpList()) { - String[] sz = s.split(":"); - seeds.add(new InetSocketAddress(sz[0], Integer.parseInt(sz[1]))); + public static boolean hasIpv4Stack(Set ipSet) { + for (String ip : ipSet) { + InetAddress inetAddress; + try { + inetAddress = InetAddress.getByName(ip); + } catch (UnknownHostException e) { + logger.warn("Get inet address failed, {}", e.getMessage()); + continue; + } + if (inetAddress instanceof Inet4Address) { + return true; + } } + return false; + } + private P2pConfig getConfig() { P2pConfig config = new P2pConfig(); - config.setSeedNodes(seeds); - config.setActiveNodes(parameter.getActiveNodes()); - config.setTrustNodes(parameter.getPassiveNodes()); + return updateConfig(config); + } + + private P2pConfig updateConfig(P2pConfig config) { + List seeds = parameter.getSeedNode().getAddressList(); + seeds.addAll(nodePersistService.dbRead()); + logger.debug("Seed InetSocketAddress: {}", seeds); + config.getSeedNodes().addAll(seeds); + config.getActiveNodes().addAll(parameter.getActiveNodes()); + config.getTrustNodes().addAll(parameter.getPassiveNodes()); config.getActiveNodes().forEach(n -> config.getTrustNodes().add(n.getAddress())); parameter.getFastForwardNodes().forEach(f -> config.getTrustNodes().add(f.getAddress())); int maxConnections = parameter.getMaxConnections(); @@ -155,12 +176,25 @@ private P2pConfig getConfig() { config.setMaxConnectionsWithSameIp(parameter.getMaxConnectionsWithSameIp()); config.setPort(parameter.getNodeListenPort()); - config.setVersion(parameter.getNodeP2pVersion()); + config.setNetworkId(parameter.getNodeP2pVersion()); config.setDisconnectionPolicyEnable(parameter.isOpenFullTcpDisconnect()); + config.setNodeDetectEnable(parameter.isNodeDetectEnable()); config.setDiscoverEnable(parameter.isNodeDiscoveryEnable()); - if (StringUtil.isNullOrEmpty(config.getIp())) { + if (StringUtils.isEmpty(config.getIp()) && hasIpv4Stack(NetUtil.getAllLocalAddress())) { config.setIp(parameter.getNodeExternalIp()); } + if (StringUtils.isNotEmpty(config.getIpv6())) { + config.getActiveNodes().remove(new InetSocketAddress(config.getIpv6(), config.getPort())); + } + if (!parameter.nodeEnableIpv6) { + config.setIpv6(null); + } + logger.info("Local ipv4: {}", config.getIp()); + logger.info("Local ipv6: {}", config.getIpv6()); + config.setTreeUrls(parameter.getDnsTreeUrls()); + if (Objects.nonNull(parameter.getDnsPublishConfig())) { + config.setPublishConfig(parameter.getDnsPublishConfig()); + } return config; } } \ No newline at end of file diff --git a/framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java b/framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java index 0c06c332bd0..9efb223fdb7 100755 --- a/framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/handshake/HelloMessage.java @@ -2,6 +2,7 @@ import com.google.protobuf.ByteString; import lombok.Getter; +import org.apache.commons.lang3.StringUtils; import org.tron.common.utils.ByteArray; import org.tron.common.utils.StringUtil; import org.tron.core.ChainBaseManager; @@ -31,11 +32,7 @@ public HelloMessage(byte[] data) throws Exception { public HelloMessage(Node from, long timestamp, ChainBaseManager chainBaseManager) { - Endpoint fromEndpoint = Endpoint.newBuilder() - .setNodeId(ByteString.copyFrom(from.getId())) - .setPort(from.getPort()) - .setAddress(ByteString.copyFrom(ByteArray.fromString(from.getHost()))) - .build(); + Endpoint fromEndpoint = getEndpointFromNode(from); BlockCapsule.BlockId gid = chainBaseManager.getGenesisBlockId(); Protocol.HelloMessage.BlockId gBlockId = Protocol.HelloMessage.BlockId.newBuilder() @@ -94,7 +91,8 @@ public long getTimestamp() { public Node getFrom() { Endpoint from = this.helloMessage.getFrom(); return new Node(from.getNodeId().toByteArray(), - ByteArray.toStr(from.getAddress().toByteArray()), from.getPort()); + ByteArray.toStr(from.getAddress().toByteArray()), + ByteArray.toStr(from.getAddressIpv6().toByteArray()), from.getPort()); } public BlockCapsule.BlockId getGenesisBlockId() { @@ -122,7 +120,7 @@ public String toString() { StringBuilder builder = new StringBuilder(); builder.append(super.toString()) - .append("from: ").append(getFrom().getInetSocketAddress()).append("\n") + .append("from: ").append(getFrom().getPreferInetSocketAddress()).append("\n") .append("timestamp: ").append(getTimestamp()).append("\n") .append("headBlockId: ").append(getHeadBlockId().getString()).append("\n") .append("nodeType: ").append(helloMessage.getNodeType()).append("\n") @@ -165,4 +163,21 @@ public boolean valid() { return true; } + + public static Endpoint getEndpointFromNode(Node node) { + Endpoint.Builder builder = Endpoint.newBuilder() + .setPort(node.getPort()); + if (node.getId() != null) { + builder.setNodeId(ByteString.copyFrom(node.getId())); + } + if (StringUtils.isNotEmpty(node.getHostV4())) { + builder.setAddress( + ByteString.copyFrom(org.tron.p2p.utils.ByteArray.fromString(node.getHostV4()))); + } + if (StringUtils.isNotEmpty(node.getHostV6())) { + builder.setAddressIpv6( + ByteString.copyFrom(org.tron.p2p.utils.ByteArray.fromString(node.getHostV6()))); + } + return builder.build(); + } } diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java index 6613ebfc581..9bb746346a6 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java @@ -67,6 +67,7 @@ public void processMessage(PeerConnection peer, TronMessage msg) throws P2pExcep if (peer.getSyncBlockRequested().containsKey(blockId)) { peer.getSyncBlockRequested().remove(blockId); + peer.getSyncBlockInProcess().add(blockId); syncService.processBlock(peer, blockMessage); } else { Item item = new Item(blockId, InventoryType.BLOCK); diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java index d1ee974cc64..bd2e428418c 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java @@ -13,6 +13,7 @@ import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.Parameter.NetConstants; +import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; import org.tron.core.exception.P2pException.TypeEnum; import org.tron.core.net.TronNetDelegate; @@ -32,6 +33,8 @@ public class ChainInventoryMsgHandler implements TronMsgHandler { @Autowired private SyncService syncService; + private final long syncFetchBatchNum = Args.getInstance().getSyncFetchBatchNum(); + @Override public void processMessage(PeerConnection peer, TronMessage msg) throws P2pException { @@ -88,7 +91,7 @@ public void processMessage(PeerConnection peer, TronMessage msg) throws P2pExcep peer.setFetchAble(true); if ((chainInventoryMessage.getRemainNum() == 0 && !peer.getSyncBlockToFetch().isEmpty()) || (chainInventoryMessage.getRemainNum() != 0 - && peer.getSyncBlockToFetch().size() > NetConstants.SYNC_FETCH_BATCH_NUM)) { + && peer.getSyncBlockToFetch().size() > syncFetchBatchNum)) { syncService.setFetchFlag(true); } else { syncService.syncNext(peer); diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandler.java index 6b5b68b1d11..5e797c084b3 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandler.java @@ -133,7 +133,7 @@ private void check(PeerConnection peer, FetchInvDataMessage fetchInvDataMsg) thr if (type == MessageTypes.TRX) { for (Sha256Hash hash : fetchInvDataMsg.getHashList()) { if (peer.getAdvInvSpread().getIfPresent(new Item(hash, InventoryType.TRX)) == null) { - throw new P2pException(TypeEnum.BAD_MESSAGE, "not spread inv: {}" + hash); + throw new P2pException(TypeEnum.BAD_MESSAGE, "not spread inv: " + hash); } } int fetchCount = peer.getPeerStatistics().messageStatistics.tronInTrxFetchInvDataElement diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/InventoryMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/InventoryMsgHandler.java index 65fa09128db..02b04d73b32 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/InventoryMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/InventoryMsgHandler.java @@ -26,8 +26,6 @@ public class InventoryMsgHandler implements TronMsgHandler { @Autowired private TransactionsMsgHandler transactionsMsgHandler; - private int maxCountIn10s = 10_000; - @Override public void processMessage(PeerConnection peer, TronMessage msg) { InventoryMessage inventoryMessage = (InventoryMessage) msg; @@ -54,25 +52,13 @@ private boolean check(PeerConnection peer, InventoryMessage inventoryMessage) { return false; } - if (type.equals(InventoryType.TRX)) { - int count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); - if (count > maxCountIn10s) { - logger.warn("Drop inv: {} size: {} from Peer {}, Inv count: {} is overload", - type, size, peer.getInetAddress(), count); - if (Args.getInstance().isOpenPrintLog()) { - logger.warn("[overload]Drop tx list is: {}", inventoryMessage.getHashList()); - } - return false; - } - - if (transactionsMsgHandler.isBusy()) { - logger.warn("Drop inv: {} size: {} from Peer {}, transactionsMsgHandler is busy", - type, size, peer.getInetAddress()); - if (Args.getInstance().isOpenPrintLog()) { - logger.warn("[isBusy]Drop tx list is: {}", inventoryMessage.getHashList()); - } - return false; + if (type.equals(InventoryType.TRX) && transactionsMsgHandler.isBusy()) { + logger.warn("Drop inv: {} size: {} from Peer {}, transactionsMsgHandler is busy", + type, size, peer.getInetAddress()); + if (Args.getInstance().isOpenPrintLog()) { + logger.warn("[isBusy]Drop tx list is: {}", inventoryMessage.getHashList()); } + return false; } return true; diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java index 37d46f6a8f3..9027034ccc7 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandler.java @@ -29,7 +29,10 @@ public void processMessage(PeerConnection peer, TronMessage msg) throws P2pExcep SyncBlockChainMessage syncBlockChainMessage = (SyncBlockChainMessage) msg; - check(peer, syncBlockChainMessage); + if (!check(peer, syncBlockChainMessage)) { + peer.disconnect(Protocol.ReasonCode.BAD_PROTOCOL); + return; + } long remainNum = 0; @@ -53,7 +56,7 @@ public void processMessage(PeerConnection peer, TronMessage msg) throws P2pExcep peer.sendMessage(new ChainInventoryMessage(blockIds, remainNum)); } - private void check(PeerConnection peer, SyncBlockChainMessage msg) throws P2pException { + private boolean check(PeerConnection peer, SyncBlockChainMessage msg) throws P2pException { List blockIds = msg.getBlockIds(); if (CollectionUtils.isEmpty(blockIds)) { throw new P2pException(TypeEnum.BAD_MESSAGE, "SyncBlockChain blockIds is empty"); @@ -61,7 +64,9 @@ private void check(PeerConnection peer, SyncBlockChainMessage msg) throws P2pExc BlockId firstId = blockIds.get(0); if (!tronNetDelegate.containBlockInMainChain(firstId)) { - throw new P2pException(TypeEnum.BAD_MESSAGE, "No first block:" + firstId.getString()); + logger.warn("Sync message from peer {} without the first block: {}", + peer.getInetSocketAddress(), firstId.getString()); + return false; } long headNum = tronNetDelegate.getHeadBlockId().getNum(); @@ -76,6 +81,8 @@ private void check(PeerConnection peer, SyncBlockChainMessage msg) throws P2pExc throw new P2pException(TypeEnum.BAD_MESSAGE, "lastSyncNum:" + lastSyncBlockId.getNum() + " gt lastNum:" + lastNum); } + + return true; } private LinkedList getLostBlockIds(List blockIds) throws P2pException { diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/TransactionsMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/TransactionsMsgHandler.java index df46c448e4d..5f8b3fcef16 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/TransactionsMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/TransactionsMsgHandler.java @@ -53,6 +53,7 @@ public void init() { } public void close() { + trxHandlePool.shutdown(); smartContractExecutor.shutdown(); } diff --git a/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java b/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java index a13240fa8ff..0499fb4f818 100644 --- a/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java +++ b/framework/src/main/java/org/tron/core/net/peer/PeerConnection.java @@ -221,7 +221,7 @@ public String log() { + "blockInProcess:%d\n", channel.getInetSocketAddress(), (now - channel.getStartTime()) / Constant.ONE_THOUSAND, - channel.getLatency(), + channel.getAvgLatency(), fastForwardBlock != null ? fastForwardBlock.getNum() : blockBothHave.getNum(), isNeedSyncFromPeer(), isNeedSyncFromUs(), @@ -293,6 +293,14 @@ public static boolean needToLog(Message msg) { return true; } + public synchronized boolean checkAndPutAdvInvRequest(Item key, Long value) { + if (advInvRequest.containsKey(key)) { + return false; + } + advInvRequest.put(key, value); + return true; + } + @Override public boolean equals(Object o) { if (!(o instanceof PeerConnection)) { diff --git a/framework/src/main/java/org/tron/core/net/peer/PeerManager.java b/framework/src/main/java/org/tron/core/net/peer/PeerManager.java index 8a402438c86..6817720dff5 100644 --- a/framework/src/main/java/org/tron/core/net/peer/PeerManager.java +++ b/framework/src/main/java/org/tron/core/net/peer/PeerManager.java @@ -89,7 +89,7 @@ private static void remove(PeerConnection peerConnection) { } public static synchronized void sortPeers() { - peers.sort(Comparator.comparingDouble(c -> c.getChannel().getLatency())); + peers.sort(Comparator.comparingDouble(c -> c.getChannel().getAvgLatency())); } public static PeerConnection getPeerConnection(Channel channel) { diff --git a/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java b/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java index b6ea7a3445f..03668d01837 100644 --- a/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java +++ b/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java @@ -281,8 +281,9 @@ private void consumerInvToFetch() { && invSender.getSize(peer) < MAX_TRX_FETCH_PER_PEER) .sorted(Comparator.comparingInt(peer -> invSender.getSize(peer))) .findFirst().ifPresent(peer -> { - invSender.add(item, peer); - peer.getAdvInvRequest().put(item, now); + if (peer.checkAndPutAdvInvRequest(item, now)) { + invSender.add(item, peer); + } invToFetch.remove(item); }); }); diff --git a/framework/src/main/java/org/tron/core/net/service/effective/EffectiveCheckService.java b/framework/src/main/java/org/tron/core/net/service/effective/EffectiveCheckService.java new file mode 100644 index 00000000000..44fdc56f938 --- /dev/null +++ b/framework/src/main/java/org/tron/core/net/service/effective/EffectiveCheckService.java @@ -0,0 +1,158 @@ +package org.tron.core.net.service.effective; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.net.InetSocketAddress; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.config.args.Args; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.TronNetService; +import org.tron.core.net.peer.PeerConnection; +import org.tron.p2p.discover.Node; +import org.tron.protos.Protocol.ReasonCode; + +@Slf4j(topic = "net") +@Component +public class EffectiveCheckService { + + @Getter + private final boolean isEffectiveCheck = Args.getInstance().isNodeEffectiveCheckEnable(); + @Autowired + private TronNetDelegate tronNetDelegate; + + private final Cache nodesCache = CacheBuilder.newBuilder() + .initialCapacity(100) + .maximumSize(10000) + .expireAfterWrite(20, TimeUnit.MINUTES).build(); + @Getter + @Setter + private volatile InetSocketAddress cur; + private final AtomicInteger count = new AtomicInteger(0); + private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( + new ThreadFactoryBuilder().setNameFormat("effective-thread-%d").build()); + private long MAX_HANDSHAKE_TIME = 60_000; + + public void init() { + if (isEffectiveCheck) { + executor.scheduleWithFixedDelay(() -> { + try { + findEffectiveNode(); + } catch (Exception e) { + logger.error("Check effective connection processing failed", e); + } + }, 60, 5, TimeUnit.SECONDS); + } else { + logger.info("EffectiveCheckService is disabled"); + } + } + + public void triggerNext() { + try { + executor.submit(this::findEffectiveNode); + } catch (Exception e) { + logger.warn("Submit effective service task failed, message:{}", e.getMessage()); + } + } + + public void close() { + if (executor != null) { + try { + executor.shutdown(); + } catch (Exception e) { + logger.error("Exception in shutdown effective service worker, {}", e.getMessage()); + } + } + } + + public boolean isIsolateLand() { + return (int) tronNetDelegate.getActivePeer().stream() + .filter(PeerConnection::isNeedSyncFromUs) + .count() == tronNetDelegate.getActivePeer().size(); + } + + //try to find node which we can sync from + private void findEffectiveNode() { + if (!isIsolateLand()) { + if (count.get() > 0) { + logger.info("Success to verify effective node {}", cur); + resetCount(); + } + return; + } + + if (cur != null) { + tronNetDelegate.getActivePeer().forEach(p -> { + if (p.getInetSocketAddress().equals(cur) + && System.currentTimeMillis() - p.getChannel().getStartTime() >= MAX_HANDSHAKE_TIME) { + // we encounter no effective connection again, so we disconnect with last used node + logger.info("Disconnect with {}", cur); + p.disconnect(ReasonCode.BELOW_THAN_ME); + } + }); + logger.info("Thread is running"); + return; + } + + List tableNodes = TronNetService.getP2pService().getConnectableNodes(); + tableNodes.sort(Comparator.comparingLong(node -> -node.getUpdateTime())); + Set usedAddressSet = new HashSet<>(); + tronNetDelegate.getActivePeer().forEach(p -> usedAddressSet.add(p.getInetSocketAddress())); + Optional chosenNode = tableNodes.stream() + .filter(node -> nodesCache.getIfPresent(node.getPreferInetSocketAddress()) == null) + .filter(node -> !usedAddressSet.contains(node.getPreferInetSocketAddress())) + .filter(node -> !TronNetService.getP2pConfig().getActiveNodes() + .contains(node.getPreferInetSocketAddress())) + .findFirst(); + if (!chosenNode.isPresent()) { + logger.warn("No available node to choose"); + return; + } + + count.incrementAndGet(); + nodesCache.put(chosenNode.get().getPreferInetSocketAddress(), true); + cur = new InetSocketAddress(chosenNode.get().getPreferInetSocketAddress().getAddress(), + chosenNode.get().getPreferInetSocketAddress().getPort()); + + logger.info("Try to get effective connection by using {} at seq {}", cur, count.get()); + TronNetService.getP2pService().connect(chosenNode.get(), future -> { + if (future.isCancelled()) { + // Connection attempt cancelled by user + cur = null; + } else if (!future.isSuccess()) { + // You might get a NullPointerException here because the future might not be completed yet. + logger.warn("Connect to chosen peer {} fail, cause:{}", cur, future.cause().getMessage()); + future.channel().close(); + cur = null; + triggerNext(); + } else { + // Connection established successfully + } + }); + } + + private void resetCount() { + count.set(0); + } + + public void onDisconnect(InetSocketAddress inetSocketAddress) { + if (inetSocketAddress.equals(cur)) { + logger.warn("Close chosen peer: {}", cur); + cur = null; + triggerNext(); + } + } +} diff --git a/framework/src/main/java/org/tron/core/net/service/fetchblock/FetchBlockService.java b/framework/src/main/java/org/tron/core/net/service/fetchblock/FetchBlockService.java index f3699c3be2e..6a5b120a896 100644 --- a/framework/src/main/java/org/tron/core/net/service/fetchblock/FetchBlockService.java +++ b/framework/src/main/java/org/tron/core/net/service/fetchblock/FetchBlockService.java @@ -41,9 +41,6 @@ public class FetchBlockService { private final long fetchTimeOut = CommonParameter.getInstance().fetchBlockTimeout; - private static final int BLOCK_FETCH_TIME_OUT_LIMIT = - 2 * Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; - private static final double BLOCK_FETCH_LEFT_TIME_PERCENT = 0.5; private final ScheduledExecutorService fetchBlockWorkerExecutor = @@ -76,12 +73,9 @@ public void fetchBlock(List sha256HashList, PeerConnection peer) { sha256HashList.stream().filter(sha256Hash -> new BlockCapsule.BlockId(sha256Hash).getNum() == chainBaseManager.getHeadBlockNum() + 1) .findFirst().ifPresent(sha256Hash -> { - if (System.currentTimeMillis() - chainBaseManager.getHeadBlockTimeStamp() - < BLOCK_FETCH_TIME_OUT_LIMIT) { - fetchBlockInfo = new FetchBlockInfo(sha256Hash, peer, System.currentTimeMillis()); - logger.info("Set fetchBlockInfo, block: {}, peer: {}, time: {}", sha256Hash, - fetchBlockInfo.getPeer().getInetAddress(), fetchBlockInfo.getTime()); - } + fetchBlockInfo = new FetchBlockInfo(sha256Hash, peer, System.currentTimeMillis()); + logger.info("Set fetchBlockInfo, block: {}, peer: {}, time: {}", sha256Hash, + fetchBlockInfo.getPeer().getInetAddress(), fetchBlockInfo.getTime()); }); } @@ -99,13 +93,6 @@ private void fetchBlockProcess(FetchBlockInfo fetchBlock) { if (null == fetchBlock) { return; } - if (System.currentTimeMillis() - chainBaseManager.getHeadBlockTimeStamp() - >= BLOCK_FETCH_TIME_OUT_LIMIT) { - this.fetchBlockInfo = null; - logger.info("Clear fetchBlockInfo due to {} ms past head block time", - BLOCK_FETCH_TIME_OUT_LIMIT); - return; - } Item item = new Item(fetchBlock.getHash(), InventoryType.BLOCK); Optional optionalPeerConnection = tronNetDelegate.getActivePeer().stream() .filter(PeerConnection::isIdle) @@ -117,8 +104,8 @@ private void fetchBlockProcess(FetchBlockInfo fetchBlock) { if (optionalPeerConnection.isPresent()) { optionalPeerConnection.ifPresent(firstPeer -> { - if (shouldFetchBlock(firstPeer, fetchBlock)) { - firstPeer.getAdvInvRequest().put(item, System.currentTimeMillis()); + if (shouldFetchBlock(firstPeer, fetchBlock) + && firstPeer.checkAndPutAdvInvRequest(item, System.currentTimeMillis())) { firstPeer.sendMessage(new FetchInvDataMessage(Collections.singletonList(item.getHash()), item.getType())); this.fetchBlockInfo = null; diff --git a/framework/src/main/java/org/tron/core/net/service/handshake/HandshakeService.java b/framework/src/main/java/org/tron/core/net/service/handshake/HandshakeService.java index 7b19c9dd3d5..aa6567d1cda 100644 --- a/framework/src/main/java/org/tron/core/net/service/handshake/HandshakeService.java +++ b/framework/src/main/java/org/tron/core/net/service/handshake/HandshakeService.java @@ -11,6 +11,7 @@ import org.tron.core.net.message.handshake.HelloMessage; import org.tron.core.net.peer.PeerConnection; import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.service.effective.EffectiveCheckService; import org.tron.core.net.service.relay.RelayService; import org.tron.p2p.discover.Node; import org.tron.protos.Protocol.ReasonCode; @@ -22,6 +23,9 @@ public class HandshakeService { @Autowired private RelayService relayService; + @Autowired + private EffectiveCheckService effectiveCheckService; + @Autowired private ChainBaseManager chainBaseManager; @@ -98,9 +102,18 @@ public void processHelloMessage(PeerConnection peer, HelloMessage msg) { return; } + if (msg.getHeadBlockId().getNum() < chainBaseManager.getHeadBlockId().getNum() + && peer.getInetSocketAddress().equals(effectiveCheckService.getCur())) { + logger.info("Peer's head block {} is below than we, peer->{}, me->{}", + peer.getInetSocketAddress(), msg.getHeadBlockId().getNum(), + chainBaseManager.getHeadBlockId().getNum()); + peer.disconnect(ReasonCode.BELOW_THAN_ME); + return; + } + peer.setHelloMessageReceive(msg); - peer.getChannel().updateLatency( + peer.getChannel().updateAvgLatency( System.currentTimeMillis() - peer.getChannel().getStartTime()); PeerManager.sortPeers(); peer.onConnect(); @@ -108,8 +121,9 @@ public void processHelloMessage(PeerConnection peer, HelloMessage msg) { private void sendHelloMessage(PeerConnection peer, long time) { Node node = new Node(TronNetService.getP2pConfig().getNodeID(), - TronNetService.getP2pConfig().getIp(), - TronNetService.getP2pConfig().getPort()); + TronNetService.getP2pConfig().getIp(), + TronNetService.getP2pConfig().getIpv6(), + TronNetService.getP2pConfig().getPort()); HelloMessage message = new HelloMessage(node, time, ChainBaseManager.getChainBaseManager()); relayService.fillHelloMessage(message, peer.getChannel()); peer.sendMessage(message); diff --git a/framework/src/main/java/org/tron/core/net/service/keepalive/KeepAliveService.java b/framework/src/main/java/org/tron/core/net/service/keepalive/KeepAliveService.java index 07ab20c3954..cb5260a880c 100644 --- a/framework/src/main/java/org/tron/core/net/service/keepalive/KeepAliveService.java +++ b/framework/src/main/java/org/tron/core/net/service/keepalive/KeepAliveService.java @@ -1,67 +1,19 @@ package org.tron.core.net.service.keepalive; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; -import org.tron.core.net.TronNetService; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; -import org.tron.core.net.message.keepalive.PingMessage; import org.tron.core.net.message.keepalive.PongMessage; import org.tron.core.net.peer.PeerConnection; -import org.tron.protos.Protocol; @Slf4j(topic = "net") @Component public class KeepAliveService { - private long KEEP_ALIVE_TIMEOUT = 10_000; - - private long PING_TIMEOUT = 20_000; - - private long PING_PERIOD = 60_000; - - private final ScheduledExecutorService executor = - Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "KeepAlive")); - - public void init() { - executor.scheduleWithFixedDelay(() -> { - try { - long now = System.currentTimeMillis(); - TronNetService.getPeers().forEach(p -> { - long pingSent = p.getChannel().pingSent; - long lastSendTime = p.getChannel().getLastSendTime(); - if (p.getChannel().waitForPong) { - if (now - pingSent > PING_TIMEOUT) { - logger.warn("Peer {} receive pong timeout", p.getInetSocketAddress()); - p.disconnect(Protocol.ReasonCode.TIME_OUT); - } - } else { - if (now - lastSendTime > KEEP_ALIVE_TIMEOUT || now - pingSent > PING_PERIOD) { - p.sendMessage(new PingMessage()); - p.getChannel().waitForPong = true; - p.getChannel().pingSent = now; - } - } - }); - } catch (Throwable t) { - logger.error("Exception in keep alive task.", t); - } - }, 2, 2, TimeUnit.SECONDS); - } - - public void close() { - executor.shutdown(); - } - public void processMessage(PeerConnection peer, TronMessage message) { if (message.getType().equals(MessageTypes.P2P_PING)) { peer.sendMessage(new PongMessage()); - } else { - peer.getChannel().updateLatency(System.currentTimeMillis() - peer.getChannel().pingSent); - peer.getChannel().waitForPong = false; } } } 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 02ff1e7a1aa..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 @@ -4,15 +4,17 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.List; +import java.util.Objects; import java.util.Timer; import java.util.TimerTask; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.JsonUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.args.Args; +import org.tron.core.db.CommonStore; import org.tron.core.net.TronNetService; import org.tron.p2p.discover.Node; @@ -20,17 +22,16 @@ @Component public class NodePersistService { private static final byte[] DB_KEY_PEERS = "peers".getBytes(); - private static final long DB_COMMIT_RATE = 1 * 60 * 1000L; + private static final long DB_COMMIT_RATE = 60 * 1000L; private static final int MAX_NODES_WRITE_TO_DB = 30; - - private boolean isNodePersist = Args.getInstance().isNodeDiscoveryPersist(); - - private ChainBaseManager chainBaseManager = ChainBaseManager.getInstance(); - - private Timer nodePersistTaskTimer = new Timer("NodePersistTaskTimer"); + private final boolean isNodePersist = CommonParameter.getInstance().isNodeDiscoveryPersist(); + @Autowired + private CommonStore commonStore; + private Timer nodePersistTaskTimer; public void init() { if (isNodePersist) { + nodePersistTaskTimer = new Timer("NodePersistTaskTimer"); nodePersistTaskTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { @@ -41,6 +42,9 @@ public void run() { } public void close() { + if (Objects.isNull(nodePersistTaskTimer)) { + return; + } try { nodePersistTaskTimer.cancel(); } catch (Exception e) { @@ -51,7 +55,7 @@ public void close() { public List dbRead() { List nodes = new ArrayList<>(); try { - byte[] nodeBytes = chainBaseManager.getCommonStore().get(DB_KEY_PEERS).getData(); + byte[] nodeBytes = commonStore.get(DB_KEY_PEERS).getData(); if (ByteArray.isEmpty(nodeBytes)) { return nodes; } @@ -70,7 +74,8 @@ private void dbWrite() { List tableNodes = TronNetService.getP2pService().getTableNodes(); tableNodes.sort(Comparator.comparingLong(value -> -value.getUpdateTime())); for (Node n : tableNodes) { - batch.add(new DBNode(n.getHost(), n.getPort())); + batch.add( + new DBNode(n.getPreferInetSocketAddress().getAddress().getHostAddress(), n.getPort())); } if (batch.size() > MAX_NODES_WRITE_TO_DB) { @@ -82,8 +87,7 @@ private void dbWrite() { logger.info("Write nodes to store: {}/{} nodes", batch.size(), tableNodes.size()); - chainBaseManager.getCommonStore() - .put(DB_KEY_PEERS, new BytesCapsule(JsonUtil.obj2Json(dbNodes).getBytes())); + commonStore.put(DB_KEY_PEERS, new BytesCapsule(JsonUtil.obj2Json(dbNodes).getBytes())); } catch (Exception e) { logger.warn("DB write nodes failed, {}", e.getMessage()); } diff --git a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java index 686799bdf81..665255a6594 100644 --- a/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java +++ b/framework/src/main/java/org/tron/core/net/service/relay/RelayService.java @@ -32,7 +32,6 @@ import org.tron.core.net.peer.Item; import org.tron.core.net.peer.PeerConnection; import org.tron.core.store.WitnessScheduleStore; -import org.tron.p2p.P2pConfig; import org.tron.p2p.connection.Channel; import org.tron.protos.Protocol; diff --git a/framework/src/main/java/org/tron/core/net/service/statistics/MessageStatistics.java b/framework/src/main/java/org/tron/core/net/service/statistics/MessageStatistics.java index 6ed67026ada..787f6ef5de2 100644 --- a/framework/src/main/java/org/tron/core/net/service/statistics/MessageStatistics.java +++ b/framework/src/main/java/org/tron/core/net/service/statistics/MessageStatistics.java @@ -143,16 +143,17 @@ private void addTcpMessage(Message msg, boolean flag) { break; case TRX: if (flag) { - tronInMessage.add(); + tronInTrx.add(); } else { - tronOutMessage.add(); + tronOutTrx.add(); } break; case BLOCK: if (flag) { tronInBlock.add(); + } else { + tronOutBlock.add(); } - tronOutBlock.add(); break; default: break; diff --git a/framework/src/main/java/org/tron/core/net/service/sync/SyncService.java b/framework/src/main/java/org/tron/core/net/service/sync/SyncService.java index 5b8ea730e99..eae134758cd 100644 --- a/framework/src/main/java/org/tron/core/net/service/sync/SyncService.java +++ b/framework/src/main/java/org/tron/core/net/service/sync/SyncService.java @@ -21,7 +21,6 @@ import org.tron.common.utils.Pair; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; -import org.tron.core.config.Parameter.NetConstants; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; import org.tron.core.exception.P2pException.TypeEnum; @@ -65,6 +64,8 @@ public class SyncService { @Setter private volatile boolean fetchFlag = false; + private final long syncFetchBatchNum = Args.getInstance().getSyncFetchBatchNum(); + public void init() { fetchExecutor.scheduleWithFixedDelay(() -> { try { @@ -113,7 +114,10 @@ public void syncNext(PeerConnection peer) { logger.warn("Peer {} is in sync", peer.getInetSocketAddress()); return; } - LinkedList chainSummary = getBlockChainSummary(peer); + LinkedList chainSummary; + synchronized (tronNetDelegate.getForkLock()) { + chainSummary = getBlockChainSummary(peer); + } peer.setSyncChainRequested(new Pair<>(chainSummary, System.currentTimeMillis())); peer.sendMessage(new SyncBlockChainMessage(chainSummary)); } catch (Exception e) { @@ -129,7 +133,7 @@ public void processBlock(PeerConnection peer, BlockMessage blockMessage) { handleFlag = true; if (peer.isIdle()) { if (peer.getRemainNum() > 0 - && peer.getSyncBlockToFetch().size() <= NetConstants.SYNC_FETCH_BATCH_NUM) { + && peer.getSyncBlockToFetch().size() <= syncFetchBatchNum) { syncNext(peer); } else { fetchFlag = true; @@ -165,7 +169,8 @@ private LinkedList getBlockChainSummary(PeerConnection peer) throws P2p if (beginBlockId.getNum() == 0) { highNoFork = high = tronNetDelegate.getHeadBlockId().getNum(); } else { - if (tronNetDelegate.containBlockInMainChain(beginBlockId)) { + if (tronNetDelegate.getKhaosDbHeadBlockId().equals(beginBlockId) + || tronNetDelegate.containBlockInMainChain(beginBlockId)) { highNoFork = high = beginBlockId.getNum(); } else { forkList = tronNetDelegate.getBlockChainHashesOnFork(beginBlockId); @@ -204,7 +209,11 @@ private LinkedList getBlockChainSummary(PeerConnection peer) throws P2p } private BlockId getBlockIdByNum(long num) throws P2pException { - BlockId head = tronNetDelegate.getHeadBlockId(); + BlockId head = tronNetDelegate.getKhaosDbHeadBlockId(); + if (num == head.getNum()) { + return head; + } + head = tronNetDelegate.getHeadBlockId(); if (num == head.getNum()) { return head; } @@ -221,7 +230,8 @@ private void startFetchSyncBlock() { send.put(peer, new LinkedList<>()); } for (BlockId blockId : peer.getSyncBlockToFetch()) { - if (requestBlockIds.getIfPresent(blockId) == null) { + if (requestBlockIds.getIfPresent(blockId) == null + && !peer.getSyncBlockInProcess().contains(blockId)) { requestBlockIds.put(blockId, peer); peer.getSyncBlockRequested().put(blockId, System.currentTimeMillis()); send.get(peer).add(blockId); @@ -247,6 +257,7 @@ private synchronized void handleSyncBlock() { } final boolean[] isProcessed = {true}; + long solidNum = tronNetDelegate.getSolidBlockId().getNum(); while (isProcessed[0]) { @@ -259,40 +270,59 @@ private synchronized void handleSyncBlock() { invalid(msg.getBlockId(), peerConnection); return; } + if (msg.getBlockId().getNum() <= solidNum) { + blockWaitToProcess.remove(msg); + peerConnection.getSyncBlockInProcess().remove(msg.getBlockId()); + return; + } final boolean[] isFound = {false}; tronNetDelegate.getActivePeer().stream() .filter(peer -> msg.getBlockId().equals(peer.getSyncBlockToFetch().peek())) .forEach(peer -> { - peer.getSyncBlockToFetch().pop(); - peer.getSyncBlockInProcess().add(msg.getBlockId()); isFound[0] = true; }); if (isFound[0]) { blockWaitToProcess.remove(msg); isProcessed[0] = true; - processSyncBlock(msg.getBlockCapsule()); + processSyncBlock(msg.getBlockCapsule(), peerConnection); + peerConnection.getSyncBlockInProcess().remove(msg.getBlockId()); } } }); } } - private void processSyncBlock(BlockCapsule block) { + private void processSyncBlock(BlockCapsule block, PeerConnection peerConnection) { boolean flag = true; + boolean attackFlag = false; BlockId blockId = block.getBlockId(); try { tronNetDelegate.validSignature(block); tronNetDelegate.processBlock(block, true); pbftDataSyncHandler.processPBFTCommitData(block); + } catch (P2pException p2pException) { + logger.error("Process sync block {} failed, type: {}", + blockId.getString(), p2pException.getType()); + attackFlag = p2pException.getType().equals(TypeEnum.BLOCK_SIGN_ERROR) + || p2pException.getType().equals(TypeEnum.BLOCK_MERKLE_ERROR); + flag = false; } catch (Exception e) { logger.error("Process sync block {} failed", blockId.getString(), e); flag = false; } + + if (attackFlag) { + invalid(blockId, peerConnection); + peerConnection.disconnect(ReasonCode.BAD_BLOCK); + return; + } + for (PeerConnection peer : tronNetDelegate.getActivePeer()) { - if (peer.getSyncBlockInProcess().remove(blockId)) { + if (blockId.equals(peer.getSyncBlockToFetch().peek())) { + peer.getSyncBlockToFetch().pop(); if (flag) { peer.setBlockBothHave(blockId); - if (peer.getSyncBlockToFetch().isEmpty()) { + if (peer.getSyncBlockToFetch().isEmpty() && peer.isFetchAble()) { syncNext(peer); } } else { diff --git a/framework/src/main/java/org/tron/core/services/NodeInfoService.java b/framework/src/main/java/org/tron/core/services/NodeInfoService.java index cd73a010258..ddf72c64410 100644 --- a/framework/src/main/java/org/tron/core/services/NodeInfoService.java +++ b/framework/src/main/java/org/tron/core/services/NodeInfoService.java @@ -27,12 +27,10 @@ import org.tron.common.prometheus.MetricTime; import org.tron.core.ChainBaseManager; import org.tron.core.db.Manager; -import org.tron.core.net.P2pEventHandlerImpl; import org.tron.core.net.TronNetService; import org.tron.core.net.peer.PeerConnection; import org.tron.core.net.peer.PeerManager; import org.tron.core.net.service.statistics.NodeStatistics; -import org.tron.core.net.service.statistics.PeerStatistics; import org.tron.core.services.WitnessProductBlockService.CheatWitnessInfo; import org.tron.p2p.P2pConfig; import org.tron.p2p.P2pService; @@ -140,7 +138,7 @@ private void setConnectInfo(NodeInfo nodeInfo) { PeerInfo peerInfo = new PeerInfo(); peerInfo.setHeadBlockWeBothHave(peerConnection.getBlockBothHave().getString()); peerInfo.setActive(peerConnection.getChannel().isActive()); - peerInfo.setAvgLatency(peerConnection.getChannel().getLatency()); + peerInfo.setAvgLatency(peerConnection.getChannel().getAvgLatency()); peerInfo.setBlockInPorcSize(peerConnection.getSyncBlockInProcess().size()); peerInfo.setConnectTime(channel.getStartTime()); peerInfo.setDisconnectTimes(nodeStatistics.getDisconnectTimes()); @@ -180,7 +178,7 @@ private void setConfigNodeInfo(NodeInfo nodeInfo) { configNodeInfo.setDiscoverEnable(parameter.isNodeDiscoveryEnable()); configNodeInfo.setActiveNodeSize(parameter.getActiveNodes().size()); configNodeInfo.setPassiveNodeSize(parameter.getPassiveNodes().size()); - configNodeInfo.setSendNodeSize(parameter.getSeedNode().getIpList().size()); + configNodeInfo.setSendNodeSize(parameter.getSeedNode().getAddressList().size()); configNodeInfo.setMaxConnectCount(parameter.getMaxConnections()); configNodeInfo.setSameIpMaxConnectCount(parameter.getMaxConnectionsWithSameIp()); configNodeInfo.setBackupListenPort(parameter.getBackupPort()); diff --git a/framework/src/main/java/org/tron/core/services/RpcApiService.java b/framework/src/main/java/org/tron/core/services/RpcApiService.java index 437714ab5bd..2a4ebca95b4 100755 --- a/framework/src/main/java/org/tron/core/services/RpcApiService.java +++ b/framework/src/main/java/org/tron/core/services/RpcApiService.java @@ -22,7 +22,6 @@ import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.AccountNetMessage; import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.Address; import org.tron.api.GrpcAPI.AssetIssueList; import org.tron.api.GrpcAPI.BlockExtention; import org.tron.api.GrpcAPI.BlockLimit; @@ -45,7 +44,6 @@ import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters; import org.tron.api.GrpcAPI.NfTRC20Parameters; -import org.tron.api.GrpcAPI.Node; import org.tron.api.GrpcAPI.NodeList; import org.tron.api.GrpcAPI.NoteParameters; import org.tron.api.GrpcAPI.NumberMessage; @@ -98,7 +96,6 @@ import org.tron.core.exception.VMIllegalException; import org.tron.core.exception.ZksnarkException; import org.tron.core.metrics.MetricsApiService; -import org.tron.core.net.TronNetService; import org.tron.core.services.filter.LiteFnQueryGrpcInterceptor; import org.tron.core.services.ratelimiter.RateLimiterInterceptor; import org.tron.core.services.ratelimiter.RpcApiAccessInterceptor; @@ -133,6 +130,7 @@ import org.tron.protos.contract.BalanceContract.AccountBalanceRequest; import org.tron.protos.contract.BalanceContract.AccountBalanceResponse; import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; +import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract; import org.tron.protos.contract.BalanceContract.DelegateResourceContract; import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; import org.tron.protos.contract.BalanceContract.TransferContract; @@ -1474,6 +1472,13 @@ public void unDelegateResource(UnDelegateResourceContract request, responseObserver); } + @Override + public void cancelAllUnfreezeV2(CancelAllUnfreezeV2Contract request, + StreamObserver responseObserver) { + createTransactionExtention(request, ContractType.CancelAllUnfreezeV2Contract, + responseObserver); + } + @Override public void proposalCreate(ProposalCreateContract request, StreamObserver responseObserver) { @@ -1555,14 +1560,7 @@ public void getTransactionCountByBlockNum(NumberMessage request, @Override public void listNodes(EmptyMessage request, StreamObserver responseObserver) { - NodeList.Builder nodeListBuilder = NodeList.newBuilder(); - TronNetService.getP2pService().getConnectableNodes().forEach(node -> { - nodeListBuilder.addNodes(Node.newBuilder().setAddress( - Address.newBuilder() - .setHost(ByteString.copyFrom(ByteArray.fromString(node.getHost()))) - .setPort(node.getPort()))); - }); - responseObserver.onNext(nodeListBuilder.build()); + responseObserver.onNext(wallet.listNodes()); responseObserver.onCompleted(); } diff --git a/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java b/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java index 35ebd9d6d6d..ae7ab75a473 100644 --- a/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java +++ b/framework/src/main/java/org/tron/core/services/filter/HttpApiAccessFilter.java @@ -1,6 +1,7 @@ package org.tron.core.services.filter; import com.alibaba.fastjson.JSONObject; +import java.net.URI; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -58,6 +59,7 @@ private boolean isDisabled(String endpoint) { boolean disabled = false; try { + endpoint = URI.create(endpoint).normalize().toString(); List disabledApiList = CommonParameter.getInstance().getDisabledApiList(); if (!disabledApiList.isEmpty()) { disabled = disabledApiList.contains(endpoint.split("/")[2].toLowerCase()); diff --git a/framework/src/main/java/org/tron/core/services/http/CancelAllUnfreezeV2Servlet.java b/framework/src/main/java/org/tron/core/services/http/CancelAllUnfreezeV2Servlet.java new file mode 100644 index 00000000000..894126e50da --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/http/CancelAllUnfreezeV2Servlet.java @@ -0,0 +1,38 @@ +package org.tron.core.services.http; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.core.Wallet; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract; + +@Component +@Slf4j(topic = "API") +public class CancelAllUnfreezeV2Servlet extends RateLimiterServlet { + + @Autowired + private Wallet wallet; + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) { + try { + PostParams params = PostParams.getPostParams(request); + CancelAllUnfreezeV2Contract.Builder build = CancelAllUnfreezeV2Contract.newBuilder(); + JsonFormat.merge(params.getParams(), build, params.isVisible()); + Transaction tx = wallet + .createTransactionCapsule(build.build(), ContractType.CancelAllUnfreezeV2Contract) + .getInstance(); + JSONObject jsonObject = JSON.parseObject(params.getParams()); + tx = Util.setTransactionPermissionId(jsonObject, tx); + response.getWriter().println(Util.printCreateTransaction(tx, params.isVisible())); + } catch (Exception e) { + Util.processError(e, response); + } + } +} diff --git a/framework/src/main/java/org/tron/core/services/http/DelegateResourceServlet.java b/framework/src/main/java/org/tron/core/services/http/DelegateResourceServlet.java index 221cc34cf7c..00994238988 100644 --- a/framework/src/main/java/org/tron/core/services/http/DelegateResourceServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/DelegateResourceServlet.java @@ -1,5 +1,6 @@ package org.tron.core.services.http; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -18,6 +19,7 @@ public class DelegateResourceServlet extends RateLimiterServlet { @Autowired private Wallet wallet; + @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { PostParams params = PostParams.getPostParams(request); @@ -26,7 +28,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Transaction tx = wallet .createTransactionCapsule(build.build(), ContractType.DelegateResourceContract) .getInstance(); - JSONObject jsonObject = JSONObject.parseObject(params.getParams()); + JSONObject jsonObject = JSON.parseObject(params.getParams()); tx = Util.setTransactionPermissionId(jsonObject, tx); response.getWriter().println(Util.printCreateTransaction(tx, params.isVisible())); } catch (Exception e) { diff --git a/framework/src/main/java/org/tron/core/services/http/EstimateEnergyServlet.java b/framework/src/main/java/org/tron/core/services/http/EstimateEnergyServlet.java index 6b82199bd0e..d88f7dd1af1 100644 --- a/framework/src/main/java/org/tron/core/services/http/EstimateEnergyServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/EstimateEnergyServlet.java @@ -4,7 +4,6 @@ import com.google.protobuf.ByteString; import io.netty.util.internal.StringUtil; import java.io.IOException; -import java.security.InvalidParameterException; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -25,26 +24,12 @@ @Slf4j(topic = "API") public class EstimateEnergyServlet extends RateLimiterServlet { - private final String functionSelector = "function_selector"; - @Autowired private Wallet wallet; protected void doGet(HttpServletRequest request, HttpServletResponse response) { } - protected void validateParameter(String contract) { - JSONObject jsonObject = JSONObject.parseObject(contract); - if (!jsonObject.containsKey("owner_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("owner_address"))) { - throw new InvalidParameterException("owner_address isn't set."); - } - if (!jsonObject.containsKey("contract_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) { - throw new InvalidParameterException("contract_address isn't set."); - } - } - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { TriggerSmartContract.Builder build = TriggerSmartContract.newBuilder(); @@ -57,21 +42,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) .collect(Collectors.joining(System.lineSeparator())); Util.checkBodySize(contract); visible = Util.getVisiblePost(contract); - validateParameter(contract); + Util.validateParameter(contract); JsonFormat.merge(contract, build, visible); JSONObject jsonObject = JSONObject.parseObject(contract); - boolean isFunctionSelectorSet = jsonObject.containsKey(functionSelector) - && !StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector)); - String data; + boolean isFunctionSelectorSet = + !StringUtil.isNullOrEmpty(jsonObject.getString(Util.FUNCTION_SELECTOR)); if (isFunctionSelectorSet) { - String selector = jsonObject.getString(functionSelector); - String parameter = jsonObject.getString("parameter"); - data = Util.parseMethod(selector, parameter); + String selector = jsonObject.getString(Util.FUNCTION_SELECTOR); + String parameter = jsonObject.getString(Util.FUNCTION_PARAMETER); + String data = Util.parseMethod(selector, parameter); build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); - } else { - build.setData(ByteString.copyFrom(new byte[0])); } + TransactionCapsule trxCap = wallet.createTransactionCapsule(build.build(), Protocol.Transaction.Contract.ContractType.TriggerSmartContract); diff --git a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java index 030adc489ed..082307fe629 100644 --- a/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java +++ b/framework/src/main/java/org/tron/core/services/http/FullNodeHttpApiService.java @@ -302,6 +302,8 @@ public class FullNodeHttpApiService implements Service { private DelegateResourceServlet delegateResourceServlet; @Autowired private UnDelegateResourceServlet unDelegateResourceServlet; + @Autowired + private CancelAllUnfreezeV2Servlet cancelAllUnfreezeV2Servlet; private static String getParamsFile(String fileName) { InputStream in = Thread.currentThread().getContextClassLoader() @@ -564,6 +566,8 @@ public void start() { "/wallet/delegateresource"); context.addServlet(new ServletHolder(unDelegateResourceServlet), "/wallet/undelegateresource"); + context.addServlet(new ServletHolder(cancelAllUnfreezeV2Servlet), + "/wallet/cancelallunfreezev2"); int maxHttpConnectNumber = Args.getInstance().getMaxHttpConnectNumber(); if (maxHttpConnectNumber > 0) { diff --git a/framework/src/main/java/org/tron/core/services/http/HttpSelfFormatFieldName.java b/framework/src/main/java/org/tron/core/services/http/HttpSelfFormatFieldName.java index 93b726bb0e5..c551259fb3e 100644 --- a/framework/src/main/java/org/tron/core/services/http/HttpSelfFormatFieldName.java +++ b/framework/src/main/java/org/tron/core/services/http/HttpSelfFormatFieldName.java @@ -144,6 +144,8 @@ public class HttpSelfFormatFieldName { //UnDelegateResourceContract AddressFieldNameMap.put("protocol.UnDelegateResourceContract.owner_address", 1); AddressFieldNameMap.put("protocol.UnDelegateResourceContract.receiver_address", 1); + //CancelAllUnfreezeV2Contract + AddressFieldNameMap.put("protocol.CancelAllUnfreezeV2Contract.owner_address", 1); AddressFieldNameMap.put("protocol.CanDelegatedMaxSizeRequestMessage.owner_address", 1); AddressFieldNameMap.put("protocol.GetAvailableUnfreezeCountRequestMessage.owner_address", 1); AddressFieldNameMap.put("protocol.CanWithdrawUnfreezeAmountRequestMessage.owner_address", 1); diff --git a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java index 53eb1067fd3..eb8b7b86257 100644 --- a/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/RateLimiterServlet.java @@ -16,6 +16,7 @@ import org.tron.common.prometheus.MetricLabels; import org.tron.common.prometheus.Metrics; import org.tron.core.config.args.Args; +import org.tron.core.services.ratelimiter.GlobalRateLimiter; import org.tron.core.services.ratelimiter.RateLimiterContainer; import org.tron.core.services.ratelimiter.RuntimeData; import org.tron.core.services.ratelimiter.adapter.DefaultBaseQqsAdapter; @@ -91,12 +92,16 @@ private void addRateContainer() { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + + RuntimeData runtimeData = new RuntimeData(req); + GlobalRateLimiter.acquire(runtimeData); + IRateLimiter rateLimiter = container.get(KEY_PREFIX_HTTP, getClass().getSimpleName()); boolean acquireResource = true; if (rateLimiter != null) { - acquireResource = rateLimiter.acquire(new RuntimeData(req)); + acquireResource = rateLimiter.acquire(runtimeData); } String url = Strings.isNullOrEmpty(req.getRequestURI()) ? MetricLabels.UNDEFINED : req.getRequestURI(); diff --git a/framework/src/main/java/org/tron/core/services/http/TriggerConstantContractServlet.java b/framework/src/main/java/org/tron/core/services/http/TriggerConstantContractServlet.java index 4c4b6908a6e..8a46ee1ed74 100644 --- a/framework/src/main/java/org/tron/core/services/http/TriggerConstantContractServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/TriggerConstantContractServlet.java @@ -4,7 +4,6 @@ import com.google.protobuf.ByteString; import io.netty.util.internal.StringUtil; import java.io.IOException; -import java.security.InvalidParameterException; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -27,26 +26,12 @@ @Slf4j(topic = "API") public class TriggerConstantContractServlet extends RateLimiterServlet { - private final String functionSelector = "function_selector"; - @Autowired private Wallet wallet; protected void doGet(HttpServletRequest request, HttpServletResponse response) { } - protected void validateParameter(String contract) { - JSONObject jsonObject = JSONObject.parseObject(contract); - if (!jsonObject.containsKey("owner_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("owner_address"))) { - throw new InvalidParameterException("owner_address isn't set."); - } - if (!jsonObject.containsKey("contract_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) { - throw new InvalidParameterException("contract_address isn't set."); - } - } - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { TriggerSmartContract.Builder build = TriggerSmartContract.newBuilder(); @@ -58,21 +43,19 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) .collect(Collectors.joining(System.lineSeparator())); Util.checkBodySize(contract); visible = Util.getVisiblePost(contract); - validateParameter(contract); + Util.validateParameter(contract); JsonFormat.merge(contract, build, visible); JSONObject jsonObject = JSONObject.parseObject(contract); - boolean isFunctionSelectorSet = jsonObject.containsKey(functionSelector) - && !StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector)); - String data; + boolean isFunctionSelectorSet = + !StringUtil.isNullOrEmpty(jsonObject.getString(Util.FUNCTION_SELECTOR)); if (isFunctionSelectorSet) { - String selector = jsonObject.getString(functionSelector); - String parameter = jsonObject.getString("parameter"); - data = Util.parseMethod(selector, parameter); + String selector = jsonObject.getString(Util.FUNCTION_SELECTOR); + String parameter = jsonObject.getString(Util.FUNCTION_PARAMETER); + String data = Util.parseMethod(selector, parameter); build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); - } else { - build.setData(ByteString.copyFrom(new byte[0])); } + TransactionCapsule trxCap = wallet .createTransactionCapsule(build.build(), ContractType.TriggerSmartContract); diff --git a/framework/src/main/java/org/tron/core/services/http/TriggerSmartContractServlet.java b/framework/src/main/java/org/tron/core/services/http/TriggerSmartContractServlet.java index 345475cbec5..6577a9e5f24 100644 --- a/framework/src/main/java/org/tron/core/services/http/TriggerSmartContractServlet.java +++ b/framework/src/main/java/org/tron/core/services/http/TriggerSmartContractServlet.java @@ -27,23 +27,19 @@ @Slf4j(topic = "API") public class TriggerSmartContractServlet extends RateLimiterServlet { - private final String functionSelector = "function_selector"; - @Autowired private Wallet wallet; protected void doGet(HttpServletRequest request, HttpServletResponse response) { } - protected void validateParameter(String contract) { + private void validateParameter(String contract) { JSONObject jsonObject = JSONObject.parseObject(contract); - if (!jsonObject.containsKey("owner_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("owner_address"))) { - throw new InvalidParameterException("owner_address isn't set."); + if (StringUtil.isNullOrEmpty(jsonObject.getString(Util.OWNER_ADDRESS))) { + throw new InvalidParameterException(Util.OWNER_ADDRESS + " isn't set."); } - if (!jsonObject.containsKey("contract_address") - || StringUtil.isNullOrEmpty(jsonObject.getString("contract_address"))) { - throw new InvalidParameterException("contract_address isn't set."); + if (StringUtil.isNullOrEmpty(jsonObject.getString(Util.CONTRACT_ADDRESS))) { + throw new InvalidParameterException(Util.CONTRACT_ADDRESS + " isn't set."); } } @@ -62,16 +58,13 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) JsonFormat.merge(contract, build, visible); JSONObject jsonObject = JSONObject.parseObject(contract); - boolean isFunctionSelectorSet = jsonObject.containsKey(functionSelector) - && !StringUtil.isNullOrEmpty(jsonObject.getString(functionSelector)); - String data; + boolean isFunctionSelectorSet = + !StringUtil.isNullOrEmpty(jsonObject.getString(Util.FUNCTION_SELECTOR)); if (isFunctionSelectorSet) { - String selector = jsonObject.getString(functionSelector); - String parameter = jsonObject.getString("parameter"); - data = Util.parseMethod(selector, parameter); + String selector = jsonObject.getString(Util.FUNCTION_SELECTOR); + String parameter = jsonObject.getString(Util.FUNCTION_PARAMETER); + String data = Util.parseMethod(selector, parameter); build.setData(ByteString.copyFrom(ByteArray.fromHexString(data))); - } else { - build.setData(ByteString.copyFrom(new byte[0])); } build.setCallTokenValue(Util.getJsonLongValue(jsonObject, "call_token_value")); diff --git a/framework/src/main/java/org/tron/core/services/http/Util.java b/framework/src/main/java/org/tron/core/services/http/Util.java index 28ec18b59ac..2cbf5d2e718 100644 --- a/framework/src/main/java/org/tron/core/services/http/Util.java +++ b/framework/src/main/java/org/tron/core/services/http/Util.java @@ -64,6 +64,13 @@ public class Util { public static final String EXTRA_DATA = "extra_data"; public static final String PARAMETER = "parameter"; + // Used for TVM http interfaces + public static final String OWNER_ADDRESS = "owner_address"; + public static final String CONTRACT_ADDRESS = "contract_address"; + public static final String FUNCTION_SELECTOR = "function_selector"; + public static final String FUNCTION_PARAMETER = "parameter"; + public static final String CALL_DATA = "data"; + public static String printTransactionFee(String transactionFee) { JSONObject jsonObject = new JSONObject(); JSONObject receipt = JSONObject.parseObject(transactionFee); @@ -213,7 +220,7 @@ public static JSONObject printTransactionToJSON(Transaction transaction, boolean .parseObject(JsonFormat.printToString(deployContract, selfType)); byte[] ownerAddress = deployContract.getOwnerAddress().toByteArray(); byte[] contractAddress = generateContractAddress(transaction, ownerAddress); - jsonTransaction.put("contract_address", ByteArray.toHexString(contractAddress)); + jsonTransaction.put(CONTRACT_ADDRESS, ByteArray.toHexString(contractAddress)); break; default: Class clazz = TransactionFactory.getContract(contract.getType()); @@ -296,7 +303,7 @@ public static Transaction packTransaction(String strTransaction, boolean selfTyp } catch (JSONException e) { logger.debug("JSONException: {}", e.getMessage()); } catch (Exception e) { - logger.error("", e); + logger.warn("{}", contractType, e); } } rawData.put("contract", contracts); @@ -536,4 +543,30 @@ public static List convertLogAddressToTronAddress(TransactionInfo transacti return newLogList; } + /** + * Validate parameters for trigger constant and estimate energy + * - Rule-1: owner address must be set + * - Rule-2: either contract address is set or call data is set + * - Rule-3: if try to deploy, function selector and call data can not be both set + * @param contract parameters in json format + * @throws InvalidParameterException if validation is not passed, this kind of exception is thrown + */ + public static void validateParameter(String contract) throws InvalidParameterException { + JSONObject jsonObject = JSONObject.parseObject(contract); + if (StringUtils.isEmpty(jsonObject.getString(OWNER_ADDRESS))) { + throw new InvalidParameterException(OWNER_ADDRESS + " isn't set."); + } + if (StringUtils.isEmpty(jsonObject.getString(CONTRACT_ADDRESS)) + && StringUtils.isEmpty(jsonObject.getString(CALL_DATA))) { + throw new InvalidParameterException("At least one of " + + CONTRACT_ADDRESS + " and " + CALL_DATA + " must be set."); + } + if (StringUtils.isEmpty(jsonObject.getString(CONTRACT_ADDRESS)) + && !StringUtils.isEmpty(jsonObject.getString(FUNCTION_SELECTOR)) + && !StringUtils.isEmpty(jsonObject.getString(CALL_DATA))) { + throw new InvalidParameterException("While trying to deploy, " + + FUNCTION_SELECTOR + " and " + CALL_DATA + " can not be both set."); + } + } + } diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java index a25bedc577d..4efc5994c0d 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcApiUtil.java @@ -216,6 +216,7 @@ public static long getTransactionAmount(Transaction.Contract contract, String ha case WithdrawBalanceContract: case WithdrawExpireUnfreezeContract: case UnfreezeBalanceV2Contract: + case CancelAllUnfreezeV2Contract: TransactionInfo transactionInfo = wallet .getTransactionInfoById(ByteString.copyFrom(ByteArray.fromHexString(hash))); amount = getAmountFromTransactionInfo(hash, contract.getType(), transactionInfo); @@ -292,6 +293,7 @@ public static long getTransactionAmount(Transaction.Contract contract, String ha case WithdrawBalanceContract: case WithdrawExpireUnfreezeContract: case UnfreezeBalanceV2Contract: + case CancelAllUnfreezeV2Contract: amount = getAmountFromTransactionInfo(hash, contract.getType(), transactionInfo); break; case UnfreezeAssetContract: @@ -334,11 +336,15 @@ public static long getAmountFromTransactionInfo(String hash, ContractType contra case WithdrawExpireUnfreezeContract: amount = transactionInfo.getWithdrawExpireAmount(); break; + case CancelAllUnfreezeV2Contract: + amount = transactionInfo.getCancelUnfreezeV2AmountMap().values() + .stream().mapToLong(v -> v).sum(); + break; default: break; } } else { - logger.error("Can't find transaction {} ", hash); + logger.warn("Can't find transaction {} ", hash); } } catch (Exception e) { logger.warn("Exception happens when get amount from transactionInfo. Exception = [{}]", diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java index b14c3e67e39..61d163a3e8a 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java @@ -1,9 +1,11 @@ package org.tron.core.services.jsonrpc; import com.googlecode.jsonrpc4j.HttpStatusCodeProvider; +import com.googlecode.jsonrpc4j.JsonRpcInterceptor; import com.googlecode.jsonrpc4j.JsonRpcServer; import com.googlecode.jsonrpc4j.ProxyUtil; import java.io.IOException; +import java.util.Collections; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -11,6 +13,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.common.parameter.CommonParameter; import org.tron.core.Wallet; import org.tron.core.db.Manager; import org.tron.core.services.NodeInfoService; @@ -29,6 +32,9 @@ public class JsonRpcServlet extends RateLimiterServlet { @Autowired private Manager manager; + @Autowired + private JsonRpcInterceptor interceptor; + @Override public void init(ServletConfig config) throws ServletException { super.init(config); @@ -57,6 +63,9 @@ public Integer getJsonRpcCode(int httpStatusCode) { rpcServer.setHttpStatusCodeProvider(httpStatusCodeProvider); rpcServer.setShouldLogInvocationErrors(false); + if (CommonParameter.getInstance().isMetricsPrometheusEnable()) { + rpcServer.setInterceptorList(Collections.singletonList(interceptor)); + } } @Override diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java b/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java index 453710b931b..9b9dbbdfe70 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java @@ -496,6 +496,7 @@ public String getStorageAt(String address, String storageIdx, String blockNumOrT StorageRowStore store = manager.getStorageRowStore(); Storage storage = new Storage(addressByte, store); storage.setContractVersion(smartContract.getVersion()); + storage.generateAddrHash(smartContract.getTrxHash().toByteArray()); DataWord value = storage.getValue(new DataWord(ByteArray.fromHexString(storageIdx))); return ByteArray.toJsonHex(value == null ? new byte[32] : value.getData()); diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/interceptor/MetricInterceptor.java b/framework/src/main/java/org/tron/core/services/jsonrpc/interceptor/MetricInterceptor.java new file mode 100644 index 00000000000..b4579fa461f --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/interceptor/MetricInterceptor.java @@ -0,0 +1,42 @@ +package org.tron.core.services.jsonrpc.interceptor; + +import com.fasterxml.jackson.databind.JsonNode; +import com.googlecode.jsonrpc4j.JsonRpcInterceptor; +import com.googlecode.jsonrpc4j.ProxyUtil; +import io.prometheus.client.Histogram; +import java.lang.reflect.Method; +import java.util.List; +import org.springframework.stereotype.Component; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.Metrics; + +@Component +public class MetricInterceptor implements JsonRpcInterceptor { + + private final ThreadLocal timer = new ThreadLocal<>(); + + @Override + public void preHandleJson(JsonNode json) { + + } + + @Override + public void preHandle(Object target, Method method, List params) { + timer.set(Metrics.histogramStartTimer(MetricKeys.Histogram.JSONRPC_SERVICE_LATENCY, + ProxyUtil.getMethodName(method))); + } + + @Override + public void postHandle(Object target, Method method, List params, JsonNode result) { + try { + Metrics.histogramObserve(timer.get()); + } finally { + timer.remove(); + } + } + + @Override + public void postHandleJson(JsonNode json) { + + } +} diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java index 65d0dd56ca9..f5f8fb7fdef 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/types/BlockResult.java @@ -84,6 +84,10 @@ public class BlockResult { @Setter private String mixHash = ByteArray.toJsonHex(new byte[32]); + public BlockResult() { + + } + public BlockResult(Block block, boolean fullTx, Wallet wallet) { BlockCapsule blockCapsule = new BlockCapsule(block); diff --git a/framework/src/main/java/org/tron/core/services/ratelimiter/GlobalRateLimiter.java b/framework/src/main/java/org/tron/core/services/ratelimiter/GlobalRateLimiter.java new file mode 100644 index 00000000000..a3b1638ac95 --- /dev/null +++ b/framework/src/main/java/org/tron/core/services/ratelimiter/GlobalRateLimiter.java @@ -0,0 +1,35 @@ +package org.tron.core.services.ratelimiter; + +import com.google.common.base.Strings; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.util.concurrent.RateLimiter; +import java.util.concurrent.TimeUnit; +import org.tron.core.config.args.Args; + +public class GlobalRateLimiter { + + private static double QPS = Args.getInstance().getRateLimiterGlobalQps(); + + private static double IP_QPS = Args.getInstance().getRateLimiterGlobalIpQps(); + + private static Cache cache = CacheBuilder.newBuilder() + .maximumSize(10000).expireAfterWrite(1, TimeUnit.HOURS).build(); + + private static RateLimiter rateLimiter = RateLimiter.create(QPS); + + public static void acquire(RuntimeData runtimeData) { + rateLimiter.acquire(); + String ip = runtimeData.getRemoteAddr(); + if (Strings.isNullOrEmpty(ip)) { + return; + } + RateLimiter r = cache.getIfPresent(ip); + if (r == null) { + r = RateLimiter.create(IP_QPS); + cache.put(ip, r); + } + r.acquire(); + } + +} diff --git a/framework/src/main/java/org/tron/core/services/ratelimiter/RateLimiterInterceptor.java b/framework/src/main/java/org/tron/core/services/ratelimiter/RateLimiterInterceptor.java index a74f89df517..d629ae05abd 100644 --- a/framework/src/main/java/org/tron/core/services/ratelimiter/RateLimiterInterceptor.java +++ b/framework/src/main/java/org/tron/core/services/ratelimiter/RateLimiterInterceptor.java @@ -107,10 +107,13 @@ public Listener interceptCall(ServerCall call, IRateLimiter rateLimiter = container .get(KEY_PREFIX_RPC, call.getMethodDescriptor().getFullMethodName()); + RuntimeData runtimeData = new RuntimeData(call); + GlobalRateLimiter.acquire(runtimeData); + boolean acquireResource = true; if (rateLimiter != null) { - acquireResource = rateLimiter.acquire(new RuntimeData(call)); + acquireResource = rateLimiter.acquire(runtimeData); } Listener listener = new ServerCall.Listener() { diff --git a/framework/src/main/java/org/tron/core/services/ratelimiter/RuntimeData.java b/framework/src/main/java/org/tron/core/services/ratelimiter/RuntimeData.java index 0f3c78b18d8..7cbadbc5435 100644 --- a/framework/src/main/java/org/tron/core/services/ratelimiter/RuntimeData.java +++ b/framework/src/main/java/org/tron/core/services/ratelimiter/RuntimeData.java @@ -2,6 +2,7 @@ import io.grpc.Grpc; import io.grpc.ServerCall; +import java.net.InetSocketAddress; import javax.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; @@ -16,7 +17,9 @@ public RuntimeData(Object o) { address = ((HttpServletRequest) o).getRemoteAddr(); } else if (o instanceof ServerCall) { try { - address = ((ServerCall) o).getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString(); + InetSocketAddress s = (InetSocketAddress) + ((ServerCall) o).getAttributes().get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR); + address = s.getAddress().getHostAddress(); } catch (Exception npe) { logger.warn("the address get from the runtime data is a null value unexpected."); } diff --git a/framework/src/main/java/org/tron/program/SolidityNode.java b/framework/src/main/java/org/tron/program/SolidityNode.java index 9884a14a62b..0ca001da7bb 100644 --- a/framework/src/main/java/org/tron/program/SolidityNode.java +++ b/framework/src/main/java/org/tron/program/SolidityNode.java @@ -7,6 +7,7 @@ import lombok.extern.slf4j.Slf4j; 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; @@ -37,7 +38,7 @@ public class SolidityNode { private AtomicLong remoteBlockNum = new AtomicLong(); - private LinkedBlockingDeque blockQueue = new LinkedBlockingDeque(100); + private LinkedBlockingDeque blockQueue = new LinkedBlockingDeque<>(100); private int exceptionSleepTime = 1000; @@ -48,7 +49,7 @@ public SolidityNode(Manager dbManager) { this.chainBaseManager = dbManager.getChainBaseManager(); resolveCompatibilityIssueIfUsingFullNodeDatabase(); ID.set(chainBaseManager.getDynamicPropertiesStore().getLatestSolidifiedBlockNum()); - databaseGrpcClient = new DatabaseGrpcClient(Args.getInstance().getTrustNodeAddr()); + databaseGrpcClient = new DatabaseGrpcClient(CommonParameter.getInstance().getTrustNodeAddr()); remoteBlockNum.set(getLastSolidityBlockNum()); } @@ -58,13 +59,13 @@ public SolidityNode(Manager dbManager) { public static void main(String[] args) { logger.info("Solidity node is running."); Args.setParam(args, Constant.TESTNET_CONF); - CommonParameter parameter = Args.getInstance(); + CommonParameter parameter = CommonParameter.getInstance(); logger.info("index switch is {}", BooleanUtils.toStringOnOff(BooleanUtils .toBoolean(parameter.getStorage().getIndexSwitch()))); - if (StringUtils.isEmpty(parameter.getTrustNodeAddr())) { + if (ObjectUtils.isEmpty(parameter.getTrustNodeAddr())) { logger.error("Trust node is not set."); return; } @@ -102,13 +103,13 @@ public static void main(String[] args) { private void start() { try { - new Thread(() -> getBlock()).start(); - new Thread(() -> processBlock()).start(); + new Thread(this::getBlock).start(); + new Thread(this::processBlock).start(); logger.info("Success to start solid node, ID: {}, remoteBlockNum: {}.", ID.get(), remoteBlockNum); } catch (Exception e) { - logger - .error("Failed to start solid node, address: {}.", Args.getInstance().getTrustNodeAddr()); + logger.error("Failed to start solid node, address: {}.", + CommonParameter.getInstance().getTrustNodeAddr()); System.exit(0); } } diff --git a/framework/src/main/java/org/tron/program/Version.java b/framework/src/main/java/org/tron/program/Version.java index 72028032c8e..20ceb88f708 100644 --- a/framework/src/main/java/org/tron/program/Version.java +++ b/framework/src/main/java/org/tron/program/Version.java @@ -4,7 +4,7 @@ public class Version { public static final String VERSION_NAME = "GreatVoyage-v4.7.1-11-ge5e347de7"; public static final String VERSION_CODE = "17686"; - private static final String VERSION = "4.7.1.1"; + private static final String VERSION = "4.7.2"; public static String getVersion() { return VERSION; diff --git a/framework/src/main/resources/config-localtest.conf b/framework/src/main/resources/config-localtest.conf index 45254446001..32f57481463 100644 --- a/framework/src/main/resources/config-localtest.conf +++ b/framework/src/main/resources/config-localtest.conf @@ -188,8 +188,6 @@ genesis.block = { accountType = "AssetIssue" address = "TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW" balance = "25000000000000000" - #priKey = D95611A9AF2A2A45359106222ED1AFED48853D9A44DEFF8DC7913F5CBA727366 - #password = 2VYRqa8qKkU1kQYiLtGv7UiFPZpE3v+Nx5E/XLpyc2Y= }, # the account of payment @@ -198,8 +196,6 @@ genesis.block = { accountType = "AssetIssue" address = "TGehVcNhud84JDCGrNHKVz9jEAVKUpbuiv" balance = "10000000000000000" - #priKey = cba92a516ea09f620a16ff7ee95ce0df1d56550a8babe9964981a7144c8a784a - #password = y6kqUW6gn2IKFv9+6Vzg3x1WVQqLq+mWSYGnFEyKeEo= }, # the account of coin burn @@ -208,8 +204,6 @@ genesis.block = { accountType = "AssetIssue" address = "THKrowiEfCe8evdbaBzDDvQjM5DGeB3s3F" balance = "-9223372036854775808" - #priKey = 8E812436A0E3323166E1F0E8BA79E19E217B2C4A53C970D4CCA0CFB1078979DF - #password = joEkNqDjMjFm4fDounnhniF7LEpTyXDUzKDPsQeJed8= } ] @@ -218,27 +212,23 @@ genesis.block = { address: TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz url = "http://Test.org", voteCount = 106 - #priKey = f4df789d3210ac881cb900464dd30409453044d2777060a0c391cbdf4c6a4f57 6666 }, // { // address: TPrLL5ckUdMaPNgJYmGv23qtYjBE34aBf8 // url = "http://Mercury.org", // voteCount = 105 - // #priKey = f5583fd20e13073900a513f333ed13db8c9e83e7e3cf37e74adacef96c5afeaa 7777 // }, // { // address: TEZBh76rouEQpB2zqYVopbRXGx7RfyWorT // #address: 27TfVERREG3FeWMHEAQ95tWHG4sb3ANn3Qe // url = "http://Venus.org", // voteCount = 104 - // #priKey = 9f5c5e48bf87cf92017313082e8cf0f58ccfce423097f0fcebf801695fc99bd4 8888 // }, // { // address: TN27wbfCLEN1gP2PZAxHgU3QZrntsLyxdj // #address: 27b8RUuyZnNPFNZGct2bZkNu9MnGWNAdH3Z // url = "http://Earth.org", // voteCount = 103 - // #priKey = 6781f44d9a2083b14fad1702b8e9ba82749162b795e2fc3f136192fc63f80de2 9999 // }, ] @@ -256,7 +246,7 @@ genesis.block = { //localWitnessAccountAddress = TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz localwitness = [ - f4df789d3210ac881cb900464dd30409453044d2777060a0c391cbdf4c6a4f57 + ] diff --git a/framework/src/main/resources/config.conf b/framework/src/main/resources/config.conf index 47635540017..67aa374eec3 100644 --- a/framework/src/main/resources/config.conf +++ b/framework/src/main/resources/config.conf @@ -202,6 +202,19 @@ node { solidityPort = 8091 } + # use your ipv6 address for node discovery and tcp connection, default false + enableIpv6 = false + + # if your node's highest block num is below than all your pees', try to acquire new connection. default false + effectiveCheckEnable = false + + dns { + # dns urls to get nodes, url format tree://{pubkey}@{domain}, default empty + treeUrls = [ + #"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes1.example.org", + ] + } + rpc { port = 50051 #solidityPort = 50061 diff --git a/framework/src/main/resources/logback.xml b/framework/src/main/resources/logback.xml index 8dcf9b6c66b..39c7f463172 100644 --- a/framework/src/main/resources/logback.xml +++ b/framework/src/main/resources/logback.xml @@ -60,7 +60,6 @@ 100 true - diff --git a/framework/src/test/java/org/tron/common/BaseTest.java b/framework/src/test/java/org/tron/common/BaseTest.java new file mode 100644 index 00000000000..1826dddea64 --- /dev/null +++ b/framework/src/test/java/org/tron/common/BaseTest.java @@ -0,0 +1,84 @@ +package org.tron.common; + +import com.google.protobuf.ByteString; +import java.io.File; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.junit.AfterClass; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.base.Param; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.protos.Protocol; + +@Slf4j +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {DefaultConfig.class}) +@DirtiesContext +public abstract class BaseTest { + + protected static String dbPath; + @Resource + protected Manager dbManager; + @Resource + protected ChainBaseManager chainBaseManager; + + @AfterClass + public static void destroy() { + Args.clearParam(); + if (StringUtils.isNotEmpty(dbPath) && FileUtil.deleteDir(new File(dbPath))) { + logger.info("Release resources successful."); + } else { + logger.info("Release resources failure."); + } + } + + public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { + long blockTime = System.currentTimeMillis() / 3000 * 3000; + if (time != 0) { + blockTime = time; + } else { + if (chainBaseManager.getHeadBlockId().getNum() != 0) { + blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; + } + } + Param param = Param.getInstance(); + Param.Miner miner = param.new Miner(privateKey, witness, witness); + BlockCapsule blockCapsule = dbManager + .generateBlock(miner, time, System.currentTimeMillis() + 1000); + Protocol.Block block = blockCapsule.getInstance(); + + Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() + .setParentHash(ByteString + .copyFrom(chainBaseManager.getDynamicPropertiesStore() + .getLatestBlockHeaderHash().getBytes())) + .setNumber(chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1) + .setTimestamp(blockTime) + .setWitnessAddress(witness) + .build(); + + ECKey ecKey = ECKey.fromPrivate(privateKey); + assert ecKey != null; + ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter + .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ByteString sign = ByteString.copyFrom(signature.toByteArray()); + + Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() + .setRawData(raw) + .setWitnessSignature(sign) + .build(); + + return block.toBuilder().setBlockHeader(blockHeader).build(); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java new file mode 100644 index 00000000000..8a5ff4f4bc2 --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java @@ -0,0 +1,90 @@ +package org.tron.common.backup; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ScheduledExecutorService; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.backup.message.KeepAliveMessage; +import org.tron.common.backup.socket.UdpEvent; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class BackupManagerTest { + + @Test + public void test() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + CommonParameter parameter = CommonParameter.getInstance(); + parameter.setBackupPriority(8); + List members = new ArrayList<>(); + members.add("127.0.0.2"); + parameter.setBackupMembers(members); + + BackupManager manager = new BackupManager(); + + Field field = manager.getClass().getDeclaredField("localIp"); + field.setAccessible(true); + field.set(manager, "127.0.0.1"); + + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.MASTER); + + field = manager.getClass().getDeclaredField("executorService"); + field.setAccessible(true); + ScheduledExecutorService executorService = (ScheduledExecutorService) field.get(manager); + manager.init(); + executorService.shutdown(); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.INIT); + + /* ip not in the members */ + manager.setStatus(BackupManager.BackupStatusEnum.INIT); + KeepAliveMessage message = new KeepAliveMessage(false, 6); + InetSocketAddress address = new InetSocketAddress("127.0.0.3", 1000); + UdpEvent event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.INIT); + + /* ip not the member */ + address = new InetSocketAddress("127.0.0.3", 1000); + message = new KeepAliveMessage(false, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.INIT); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + address = new InetSocketAddress("127.0.0.2", 1000); + message = new KeepAliveMessage(false, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.INIT); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + message = new KeepAliveMessage(false, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.SLAVER); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + manager.setStatus(BackupManager.BackupStatusEnum.INIT); + message = new KeepAliveMessage(true, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.SLAVER); + + manager.setStatus(BackupManager.BackupStatusEnum.MASTER); + message = new KeepAliveMessage(false, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.MASTER); + + message = new KeepAliveMessage(true, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.SLAVER); + + } +} diff --git a/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java b/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java new file mode 100644 index 00000000000..a93e044db03 --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java @@ -0,0 +1,32 @@ +package org.tron.common.backup; + +import static org.tron.common.backup.message.UdpMessageTypeEnum.BACKUP_KEEP_ALIVE; + +import org.junit.Test; +import org.testng.Assert; +import org.tron.common.backup.message.KeepAliveMessage; +import org.tron.protos.Discover; + +public class KeepAliveMessageTest { + + @Test + public void test() throws Exception { + KeepAliveMessage m1 = new KeepAliveMessage(true, 10); + Assert.assertTrue(m1.getFlag()); + Assert.assertEquals(m1.getPriority(), 10); + Assert.assertEquals(m1.getType(), BACKUP_KEEP_ALIVE); + Assert.assertEquals(m1.getFrom(), null); + Assert.assertEquals(m1.getTimestamp(), 0); + Assert.assertEquals(m1.getData().length + 1, m1.getSendData().length); + + + Discover.BackupMessage backupMessage = Discover.BackupMessage.newBuilder() + .setFlag(true).setPriority(10).build(); + KeepAliveMessage m2 = new KeepAliveMessage(backupMessage.toByteArray()); + Assert.assertTrue(m2.getFlag()); + Assert.assertEquals(m2.getPriority(), 10); + Assert.assertEquals(m2.getType(), BACKUP_KEEP_ALIVE); + + Assert.assertEquals(m2.getMessageId().getBytes(), m1.getMessageId().getBytes()); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java b/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java new file mode 100644 index 00000000000..e3ded4a23e5 --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java @@ -0,0 +1,23 @@ +package org.tron.common.backup; + +import static org.tron.common.backup.message.UdpMessageTypeEnum.BACKUP_KEEP_ALIVE; +import static org.tron.common.backup.message.UdpMessageTypeEnum.UNKNOWN; + +import org.junit.Test; +import org.testng.Assert; +import org.tron.common.backup.message.UdpMessageTypeEnum; + +public class UdpMessageTypeEnumTest { + + @Test + public void test() { + UdpMessageTypeEnum type = UdpMessageTypeEnum.fromByte((byte) 5); + Assert.assertEquals(type.getType(), (byte) 0x05); + Assert.assertEquals(type, BACKUP_KEEP_ALIVE); + + + type = UdpMessageTypeEnum.fromByte((byte) 1); + Assert.assertEquals(type.getType(), (byte) 0xFF); + Assert.assertEquals(type, UNKNOWN); + } +} diff --git a/framework/src/test/java/org/tron/common/config/args/ArgsTest.java b/framework/src/test/java/org/tron/common/config/args/ArgsTest.java index 5b391f0d38d..7ad8069db06 100644 --- a/framework/src/test/java/org/tron/common/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/common/config/args/ArgsTest.java @@ -5,22 +5,27 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.tron.common.parameter.RateLimiterInitialization; import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.config.args.Args; + + public class ArgsTest { + private static final String dbPath = "output_arg_test"; + @Before public void init() { - Args.setParam(new String[]{"--output-directory", "output-directory", "--debug"}, - Constant.TEST_CONF); + Args.setParam(new String[]{"--output-directory", dbPath, "--p2p-disable", "true", + "--debug"}, Constant.TEST_CONF); } @After public void destroy() { Args.clearParam(); - FileUtil.deleteDir(new File("output-directory")); + FileUtil.deleteDir(new File(dbPath)); } @Test @@ -30,5 +35,14 @@ public void testConfig() { Assert.assertEquals(Args.getInstance().getNodeDiscoveryPingTimeout(), 15_000); Assert.assertEquals(Args.getInstance().getMaxFastForwardNum(), 3); Assert.assertEquals(Args.getInstance().getBlockCacheTimeout(), 60); + Assert.assertEquals(Args.getInstance().isNodeDetectEnable(), false); + Assert.assertFalse(Args.getInstance().isNodeEffectiveCheckEnable()); + Assert.assertEquals(Args.getInstance().getRateLimiterGlobalQps(), 1000); + Assert.assertEquals(Args.getInstance().getRateLimiterGlobalIpQps(), 1000); + Assert.assertEquals(Args.getInstance().p2pDisable, true); + Assert.assertEquals(Args.getInstance().getMaxTps(), 1000); + RateLimiterInitialization rateLimiter = Args.getInstance().getRateLimiterInitialization(); + Assert.assertEquals(rateLimiter.getHttpMap().size(), 1); + Assert.assertEquals(rateLimiter.getRpcMap().size(), 0); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java index ebb12f25284..4e3a78461f2 100644 --- a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java +++ b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java @@ -12,6 +12,11 @@ import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.Sha256Hash; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ public class BouncyCastleTest { private String privString = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index facdcaccccc..bf268f14320 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -19,6 +19,11 @@ import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.core.Wallet; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ @Slf4j public class ECKeyTest { diff --git a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java index 80d355eb2cf..62e800679c1 100644 --- a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java @@ -19,6 +19,11 @@ import org.tron.common.crypto.sm2.SM2Signer; import org.tron.core.Wallet; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ @Slf4j public class SM2KeyTest { diff --git a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java index bed38852ef3..b413127db53 100644 --- a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java @@ -8,35 +8,26 @@ import org.bouncycastle.util.encoders.Hex; import org.junit.Test; import org.tron.common.crypto.sm2.SM2; +import org.tron.common.utils.PublicMethod; @Slf4j public class SignatureInterfaceTest { - private String SM2_privString = "128B2FA8BD433C6C068C8D803DFF79792A519A5517" - + "1B1B650C23661D15897263"; + private String SM2_privString = PublicMethod.getSM2RandomPrivateKey(); private byte[] SM2_privateKey = Hex.decode(SM2_privString); - private String SM2_pubString = "04d5548c7825cbb56150a3506cd57464af8a1ae0519" - + "dfaf3c58221dc810caf28dd921073768fe3d59ce54e79a49445cf73fed23086537" - + "027264d168946d479533e"; - private String SM2_compressedPubString = - "02d5548c7825cbb56150a3506cd57464af8a1ae0519dfaf3c58221dc810caf28dd"; + private String SM2_pubString = PublicMethod.getSM2PublicByPrivateKey(SM2_privString); private byte[] SM2_pubKey = Hex.decode(SM2_pubString); - private byte[] SM2_compressedPubKey = Hex.decode(SM2_compressedPubString); - private String SM2_address = "62e49e4c2f4e3c0653a02f8859c1e6991b759e87"; + private String SM2_address = PublicMethod.getSM2AddressByPrivateKey(SM2_privString); - - private String EC_privString = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; + private String EC_privString = PublicMethod.getRandomPrivateKey(); private byte[] EC_privateKey = Hex.decode(EC_privString); - private String EC_pubString = "040947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f698ccc" - + "8ad75aa17564ae80a20bb044ee7a6d903e8e8df624b089c95d66a0570f051e5a05b"; - private String EC_compressedPubString = - "030947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f6" + "98ccc8ad"; + private String EC_pubString = PublicMethod.getPublicByPrivateKey(EC_privString); private byte[] EC_pubKey = Hex.decode(EC_pubString); - private byte[] EC_compressedPubKey = Hex.decode(EC_compressedPubString); - private String EC_address = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + private String EC_address = PublicMethod.getHexAddressByPrivateKey(EC_privString); + @Test @@ -83,11 +74,12 @@ public void testAddress() { SignInterface sign = new SM2(SM2_pubKey, false); byte[] prefix_address = sign.getAddress(); byte[] address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - assertEquals(SM2_address, Hex.toHexString(address)); - + byte[] addressTmp = Arrays.copyOfRange(Hex.decode(SM2_address), 1, prefix_address.length); + assertEquals(Hex.toHexString(addressTmp), Hex.toHexString(address)); sign = new ECKey(EC_pubKey, false); prefix_address = sign.getAddress(); address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - assertEquals(EC_address, Hex.toHexString(address)); + byte[] ecAddressTmp = Arrays.copyOfRange(Hex.decode(EC_address), 1, prefix_address.length); + assertEquals(Hex.toHexString(ecAddressTmp), Hex.toHexString(address)); } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java index c2bf24ba383..8ff8167f52e 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java @@ -4,6 +4,8 @@ import java.util.List; import org.junit.Assert; import org.junit.Test; +import org.tron.common.logsfilter.trigger.BlockLogTrigger; +import org.tron.common.logsfilter.trigger.TransactionLogTrigger; public class EventLoaderTest { @@ -24,8 +26,57 @@ public void launchNativeQueue() { config.setTriggerConfigList(triggerConfigList); - Assert.assertEquals(true, EventPluginLoader.getInstance().start(config)); + Assert.assertTrue(EventPluginLoader.getInstance().start(config)); EventPluginLoader.getInstance().stopPlugin(); } + + @Test + public void testBlockLogTrigger() { + BlockLogTrigger blt = new BlockLogTrigger(); + blt.setBlockHash(blt.getBlockHash()); + blt.setBlockNumber(blt.getBlockNumber()); + blt.setTransactionSize(blt.getTransactionSize()); + blt.setLatestSolidifiedBlockNumber(blt.getLatestSolidifiedBlockNumber()); + blt.setTriggerName(blt.getTriggerName()); + blt.setTimeStamp(blt.getTimeStamp()); + blt.setTransactionList(blt.getTransactionList()); + Assert.assertNotNull(blt.toString()); + } + + @Test + public void testTransactionLogTrigger() { + TransactionLogTrigger tlt = new TransactionLogTrigger(); + tlt.setBlockHash(tlt.getBlockHash()); + tlt.setBlockNumber(tlt.getBlockNumber()); + tlt.setTransactionId(tlt.getTransactionId()); + tlt.setLatestSolidifiedBlockNumber(tlt.getLatestSolidifiedBlockNumber()); + tlt.setTriggerName(tlt.getTriggerName()); + tlt.setTimeStamp(tlt.getTimeStamp()); + tlt.setEnergyFee(tlt.getEnergyFee()); + tlt.setNetFee(tlt.getNetFee()); + tlt.setEnergyUsage(tlt.getEnergyUsage()); + tlt.setAssetAmount(tlt.getAssetAmount()); + tlt.setContractAddress(tlt.getContractAddress()); + tlt.setResult(tlt.getResult()); + tlt.setContractResult(tlt.getContractResult()); + tlt.setContractType(tlt.getContractType()); + tlt.setContractCallValue(tlt.getContractCallValue()); + tlt.setFromAddress(tlt.getFromAddress()); + tlt.setToAddress(tlt.getToAddress()); + tlt.setTransactionIndex(tlt.getTransactionIndex()); + tlt.setFeeLimit(tlt.getFeeLimit()); + tlt.setCumulativeEnergyUsed(tlt.getCumulativeEnergyUsed()); + tlt.setData(tlt.getData()); + tlt.setOriginEnergyUsage(tlt.getOriginEnergyUsage()); + tlt.setEnergyUsageTotal(tlt.getEnergyUsageTotal()); + tlt.setNetUsage(tlt.getNetUsage()); + tlt.setAssetName(tlt.getAssetName()); + tlt.setInternalTransactionList(tlt.getInternalTransactionList()); + tlt.setPreCumulativeLogCount(tlt.getPreCumulativeLogCount()); + tlt.setLogList(tlt.getLogList()); + tlt.setEnergyUnitPrice(tlt.getEnergyUnitPrice()); + tlt.setTimeStamp(1L); + Assert.assertNotNull(tlt.toString()); + } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java index a9b06c0e039..b5339156d9a 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java @@ -11,6 +11,7 @@ import org.tron.common.crypto.Hash; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.WalletUtil; import org.tron.core.Wallet; import org.tron.core.vm.LogInfoTriggerParser; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; @@ -57,6 +58,8 @@ public synchronized void testEventParser() { + "000000000"; ABI abi = TvmTestUtils.jsonStr2Abi(abiStr); + Assert.assertFalse(WalletUtil.isConstant(abi, new byte[3])); + byte[] data = ByteArray.fromHexString(dataStr); List topicList = new LinkedList<>(); topicList.add(Hash.sha3(eventSign.getBytes())); diff --git a/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java b/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java index f5101af19af..3c021d715cc 100644 --- a/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java +++ b/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java @@ -1,21 +1,14 @@ package org.tron.common.runtime; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -25,54 +18,36 @@ import org.tron.protos.Protocol.AccountType; @Slf4j -public class InheritanceTest { +public class InheritanceTest extends BaseTest { - private static final String dbPath = "output_InheritanceTest"; private static final String OWNER_ADDRESS; - private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static RepositoryImpl repository; + private RepositoryImpl repository; + private static boolean init; static { + dbPath = "output_InheritanceTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** * pragma solidity ^0.4.19; - * * contract foo { uint256 public id=10; function getNumber() returns (uint256){return 100;} * function getName() returns (string){ return "foo"; } } - * * contract bar is foo { function getName() returns (string) { return "bar"; } function getId() * returns(uint256){return id;} } */ @@ -119,7 +94,7 @@ public void inheritanceTest() /* ========================== CALL getName() return child value ============================= */ byte[] triggerData1 = TvmTestUtils.parseAbi("getName()", ""); - runtime = TvmTestUtils + Runtime runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(callerAddress, contractAddress, triggerData1, 0, 1000000, repository, null); diff --git a/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java b/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java index 22fb44bfacf..de2c32d2731 100644 --- a/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java +++ b/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java @@ -1,22 +1,15 @@ package org.tron.common.runtime; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -26,55 +19,38 @@ import org.tron.protos.Protocol.AccountType; @Slf4j -public class InternalTransactionComplexTest { +public class InternalTransactionComplexTest extends BaseTest { - private static final String dbPath = "output_InternalTransactionComplexTest"; private static final String OWNER_ADDRESS; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; + private static boolean init; static { + dbPath = "output_InternalTransactionComplexTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug", "--support-constant"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** * pragma solidity 0.4.24; - * * // this is to test wither the TVM is returning vars from one contract calling another // * contract's functions. - * * contract callerContract { // lets set up our instance of the new contract calledContract * CALLED_INSTANCE; // lets set the contract instance address in the constructor * constructor(address _addr) public { CALLED_INSTANCE = calledContract(_addr); } // lets create a @@ -85,7 +61,6 @@ public static void destroy() { * in to temp vars (bool _bool, uint256 _uint, bytes32 _bytes32) = CALLED_INSTANCE.testReturns(); * // lets write those temp vars to state testCallbackReturns_.someBool = _bool; * testCallbackReturns_.someUint = _uint; testCallbackReturns_.someBytes32 = _bytes32; } } - * * contract calledContract { function testReturns() external pure returns(bool, uint256, bytes32) * { return(true, 314159, 0x123456); } } */ diff --git a/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java b/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java index 8fa590eb4d8..393a68a0794 100644 --- a/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java +++ b/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java @@ -3,29 +3,23 @@ import static org.tron.core.capsule.utils.TransactionUtil.buildTransactionInfoInstance; import static org.tron.core.utils.TransactionUtil.generateContractAddress; -import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -41,22 +35,18 @@ @Slf4j -public class ProgramResultTest { +public class ProgramResultTest extends BaseTest { - private static final String dbPath = "output_InternalTransactionComplexTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; + private static boolean init; static { + dbPath = "output_InternalTransactionComplexTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug", "--support-constant"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } @@ -64,29 +54,18 @@ public class ProgramResultTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); repository.addBalance(Hex.decode(TRANSFER_TO), 0); repository.commit(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** @@ -127,8 +106,8 @@ public void uniqueInternalTransactionHashTest() internalTransaction -> hashList.add(Hex.toHexString(internalTransaction.getHash()))); // No dup List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)).entrySet().stream() - .filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) + .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum)).entrySet().stream() + .filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); Assert.assertEquals(dupHash.size(), 0); } @@ -307,27 +286,27 @@ public void successAndFailResultTest() new DataWord(internalTransactionsList.get(0).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(0).getNote(), "create"); - Assert.assertEquals(internalTransactionsList.get(0).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(0).isRejected()); Assert.assertEquals(internalTransactionsList.get(1).getValue(), 5); Assert.assertEquals(internalTransactionsList.get(1).getSender(), aContract); Assert.assertEquals( new DataWord(internalTransactionsList.get(1).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(1).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(1).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(1).isRejected()); Assert.assertEquals(internalTransactionsList.get(2).getValue(), 0); Assert.assertEquals(internalTransactionsList.get(2).getSender(), aContract); Assert.assertEquals( new DataWord(internalTransactionsList.get(2).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(2).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(2).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(2).isRejected()); Assert.assertEquals(internalTransactionsList.get(3).getValue(), 1); Assert.assertEquals(new DataWord(internalTransactionsList.get(3).getSender()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(3).getTransferToAddress(), cContract); Assert.assertEquals(internalTransactionsList.get(3).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(3).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(3).isRejected()); checkTransactionInfo(traceSuccess, trx1, null, internalTransactionsList); // ======================================= Test Fail ======================================= @@ -352,28 +331,28 @@ public void successAndFailResultTest() new DataWord(internalTransactionsListFail.get(0).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(0).getNote(), "create"); - Assert.assertEquals(internalTransactionsListFail.get(0).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(0).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(1).getValue(), 5); Assert.assertEquals(internalTransactionsListFail.get(1).getSender(), aContract); Assert.assertEquals( new DataWord(internalTransactionsListFail.get(1).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(1).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(1).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(1).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(2).getValue(), 0); Assert.assertEquals(internalTransactionsListFail.get(2).getSender(), aContract); Assert.assertEquals( new DataWord(internalTransactionsListFail.get(2).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(2).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(2).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(2).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(3).getValue(), 1); Assert.assertEquals( new DataWord(internalTransactionsListFail.get(3).getSender()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(3).getTransferToAddress(), cContract); Assert.assertEquals(internalTransactionsListFail.get(3).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(3).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(3).isRejected()); checkTransactionInfo(traceFailed, trx2, null, internalTransactionsListFail); } @@ -520,14 +499,14 @@ public void suicideResultTest() .getInternalTransactions(); Assert .assertEquals(dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getBalance(), 1000); - Assert.assertEquals(dbManager.getAccountStore().get(suicideContract), null); + Assert.assertNull(dbManager.getAccountStore().get(suicideContract)); Assert.assertEquals(internalTransactionsList.get(0).getValue(), 1000); Assert.assertEquals(new DataWord(internalTransactionsList.get(0).getSender()).getLast20Bytes(), new DataWord(suicideContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(0).getTransferToAddress(), Hex.decode(TRANSFER_TO)); Assert.assertEquals(internalTransactionsList.get(0).getNote(), "suicide"); - Assert.assertEquals(internalTransactionsList.get(0).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(0).isRejected()); checkTransactionInfo(trace, trx, null, internalTransactionsList); } diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java index cd23edbcb5e..04b08d3a58d 100644 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java @@ -3,26 +3,19 @@ import static org.tron.common.runtime.TvmTestUtils.generateDeploySmartContractAndGetTransaction; import static org.tron.common.runtime.TvmTestUtils.generateTriggerSmartContractAndGetTransaction; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.actuator.VMActuator; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -38,31 +31,28 @@ @Slf4j -public class RuntimeImplTest { +public class RuntimeImplTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private Repository repository; - private String dbPath = "output_RuntimeImplTest"; - private Application AppT; - private byte[] callerAddress; - private long callerTotalBalance = 4_000_000_000L; - private byte[] creatorAddress; - private long creatorTotalBalance = 3_000_000_000L; + private static final byte[] callerAddress; + private final long callerTotalBalance = 4_000_000_000L; + private static final byte[] creatorAddress; + private final long creatorTotalBalance = 3_000_000_000L; - /** - * Init data. - */ - @Before - public void init() { + static { + dbPath = "output_RuntimeImplTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); callerAddress = Hex .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"); creatorAddress = Hex .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abd"); - dbManager = context.getBean(Manager.class); + } + + /** + * Init data. + */ + @Before + public void init() { dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(5_000_000_000L); // unit is trx repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); @@ -117,11 +107,10 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; Transaction trx = generateDeploySmartContractAndGetTransaction(contractName, creatorAddress, ABI, - code, value, feeLimit, consumeUserResourcePercent, libraryAddressPair); + code, value, feeLimit, consumeUserResourcePercent, null); RuntimeImpl runtimeImpl = new RuntimeImpl(); runtimeImpl.execute( @@ -167,7 +156,6 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr expectEnergyLimit4); feeLimit = 3_000_000_000L; - value = 10L; long expectEnergyLimit5 = 20_009_999L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -175,7 +163,6 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr expectEnergyLimit5); feeLimit = 3_000L; - value = 10L; long expectEnergyLimit6 = 30L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -207,11 +194,10 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -229,8 +215,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -245,8 +229,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_005_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -277,8 +259,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() repository.putAccountValue(callerAddress, callerAccount); repository.commit(); - value = 10L; - feeLimit = 5_000_000_000L; long expectEnergyLimit5 = 30_014_999L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -311,11 +291,10 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() + "5060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc5" + "65b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce2576" + "54c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -333,8 +312,6 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -349,8 +326,6 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_005_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -391,11 +366,10 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -413,8 +387,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -429,8 +401,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -445,21 +415,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() .getTotalEnergyLimitWithFixRatio(creatorAccount, callerAccount, contract, feeLimit, value), expectEnergyLimit3); - - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } } diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java index e983ce12647..b40b927c5ec 100644 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java @@ -2,23 +2,17 @@ import static org.tron.core.db.TransactionTrace.convertToTronAddress; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.DataWord; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -27,24 +21,19 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.DataWord; @Slf4j -public class RuntimeTransferComplexTest { +public class RuntimeTransferComplexTest extends BaseTest { - private static final String dbPath = "output_RuntimeTransferComplexTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; + private static boolean init; static { + dbPath = "output_RuntimeTransferComplexTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } @@ -52,29 +41,18 @@ public class RuntimeTransferComplexTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), 1000000000); repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); repository.addBalance(Hex.decode(TRANSFER_TO), 10); repository.commit(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** @@ -132,7 +110,7 @@ public void TransferTrxToContractAccountFailIfNotPayable() consumeUserResourcePercent, null); byte[] contractAddress = WalletUtil.generateContractAddress(trx); runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, repository, null); - Assert.assertNotNull(runtime.getRuntimeError().contains("REVERT")); + Assert.assertTrue(runtime.getRuntimeError().contains("REVERT")); Assert.assertNull(dbManager.getAccountStore().get(contractAddress)); recoverDeposit(); } @@ -194,34 +172,25 @@ public void TransferTrxToContractAccountWhenTriggerAContract() * payable { CALLED_INSTANCE = calledContract(_addr); } // expect calledContract -5, toAddress +5 * function testCallTransferToInCalledContract(address toAddress) { * CALLED_INSTANCE.transferTo(toAddress); } - * * // expect calledContract -0, toAddress +0 function testRevertForCall(address toAddress){ * CALLED_INSTANCE.transferTo(toAddress); revert(); } function testExceptionForCall(address * toAddress){ CALLED_INSTANCE.transferTo(toAddress); assert(1==2); } // expect c +100 -5, * toAddress +0 function testTransferToInCreatedContract(address toAddress) payable * returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); return address(c); } - * * // expect c +100 -5, toAddress not exist function testRevertForCreate(address toAddress) * payable returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); revert(); return address(c); } - * * // expect c +100 -5, toAddress not exist function testExceptionForCreate(address toAddress) * payable returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); assert(1==2); return address(c); } - * * function getBalance() public view returns(uint256){ return this.balance; } } - * * contract calledContract { constructor() payable {} function transferTo(address toAddress) * payable{ toAddress.transfer(5); } - * * function getBalance() public view returns(uint256){ return this.balance; } - * * } - * * contract createdContract { constructor() payable {} function transferTo(address toAddress){ * toAddress.transfer(5); } - * * function getBalance() public view returns(uint256){ return this.balance; } } */ @@ -352,8 +321,6 @@ public void TransferCallValueTestWhenUsingCallAndCreate() .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData6, triggerCallValue, feeLimit); runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction6, repository, null); - byte[] createdAddress3 = convertToTronAddress( - new DataWord(runtime.getResult().getHReturn()).getLast20Bytes()); Assert.assertTrue(Hex.toHexString(new DataWord(createdAddress2).getLast20Bytes()) .equalsIgnoreCase("0000000000000000000000000000000000000000")); Assert.assertTrue(runtime.getRuntimeError().contains("Invalid operation code: opCode[fe];")); @@ -394,10 +361,9 @@ private byte[] deployCalledContract() long feeLimit = 100000000; long consumeUserResourcePercent = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, repository, null); - return contractAddress; } private byte[] deployCallerContract(byte[] calledAddress) @@ -475,14 +441,12 @@ private byte[] deployCallerContract(byte[] calledAddress) long value = 1000; long feeLimit = 100000000; long consumeUserResourcePercent = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, callerAddress, callerABI, callerCode, value, feeLimit, consumeUserResourcePercent, null, repository, null); - return contractAddress; } private void recoverDeposit() { - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); } diff --git a/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java b/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java index a90010f3043..ec2cd5a5e02 100644 --- a/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java +++ b/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java @@ -11,6 +11,9 @@ import org.bouncycastle.util.encoders.Hex; import org.tron.common.crypto.Hash; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.Parameter.CommonConstant; +import org.tron.common.utils.client.WalletClient; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; @@ -23,15 +26,12 @@ import org.tron.core.store.StoreFactory; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; + import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; /** @@ -621,7 +621,7 @@ public static CreateSmartContract createSmartContract(byte[] owner, String contr String abiString, String code, long value, long consumeUserResourcePercent) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - SmartContract.ABI abi = PublicMethed.jsonStr2Abi(abiString); + SmartContract.ABI abi = jsonStr2Abi(abiString); if (abi == null) { return null; } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java index 0f3cae8476a..ffc3a44e730 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmCompatibleEvmTest.java @@ -13,14 +13,15 @@ import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; + import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class AllowTvmCompatibleEvmTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java index 42725d1cbd7..864a583050b 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/AllowTvmLondonTest.java @@ -10,6 +10,7 @@ import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -17,7 +18,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class AllowTvmLondonTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java index f8a4f1ef0bb..a0c87da01c6 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java @@ -17,24 +17,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -53,32 +47,27 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeOutOfTimeTest { +public class BandWidthRuntimeOutOfTimeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeOutOfTimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; + private static final String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static boolean init; static { + dbPath = "output_bandwidth_runtime_out_of_time_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -89,17 +78,16 @@ public class BandWidthRuntimeOutOfTimeTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } - private String trx2ContractAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647828000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -123,16 +111,7 @@ public static void init() { .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule2); dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -216,8 +195,7 @@ private byte[] createContract() TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); owner = dbManager.getAccountStore() diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java index 68fa9e12fa7..37167988f34 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java @@ -17,24 +17,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -55,32 +49,26 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeOutOfTimeWithCheckTest { +public class BandWidthRuntimeOutOfTimeWithCheckTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeOutOfTimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static boolean init; static { + dbPath = "output_bandwidth_runtime_out_of_time_with_check_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -91,17 +79,16 @@ public class BandWidthRuntimeOutOfTimeWithCheckTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } - private String trx2ContractAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647837000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -125,16 +112,7 @@ public static void init() { .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule2); dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -172,9 +150,7 @@ public void testSuccess() { Assert.assertEquals(990000000, balance); Assert.assertEquals(9950000 * Constant.SUN_PER_ENERGY, balance + energy * Constant.SUN_PER_ENERGY); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java index 5e6663e8cfe..20e8e11535a 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java @@ -17,26 +17,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -53,21 +47,19 @@ import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -public class BandWidthRuntimeTest { +public class BandWidthRuntimeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; + private static final String dbDirectory = "db_BandWidthRuntimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; + private static boolean init; - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - private static String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - - static { + @BeforeClass + public static void init() { + dbPath = "output_bandwidth_runtime_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -77,16 +69,16 @@ public class BandWidthRuntimeTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); + @Before + public void before() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526547838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -122,25 +114,13 @@ public static void init() { dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test public void testSuccess() { try { byte[] contractAddress = createContract(); - AccountCapsule triggerOwner = dbManager.getAccountStore() - .get(Commons.decodeFromBase58Check(TriggerOwnerAddress)); - long energy = triggerOwner.getEnergyUsage(); TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, "setCoin(uint256)", "3", false, 0, Commons.decodeFromBase58Check(TriggerOwnerAddress)); @@ -151,15 +131,14 @@ public void testSuccess() { TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); - triggerOwner = dbManager.getAccountStore() + AccountCapsule triggerOwner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(TriggerOwnerAddress)); - energy = triggerOwner.getEnergyUsage(); + long energy = triggerOwner.getEnergyUsage(); long balance = triggerOwner.getBalance(); Assert.assertEquals(45706, trace.getReceipt().getEnergyUsageTotal()); Assert.assertEquals(45706, energy); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java index 37e21b086ea..0e7f79eb42f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java @@ -17,26 +17,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -57,34 +49,28 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeWithCheckTest { +public class BandWidthRuntimeWithCheckTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; + private static final String dbDirectory = "db_BandWidthRuntimeWithCheckTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeWithCheckTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - private static String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; + private static boolean init; static { + dbPath = "output_bandwidth_runtime_with_check_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -94,17 +80,16 @@ public class BandWidthRuntimeWithCheckTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -134,17 +119,7 @@ public static void init() { accountCapsule3.setFrozenForEnergy(10_000_000L, 0L); dbManager.getAccountStore() .put(Commons.decodeFromBase58Check(TriggerOwnerTwoAddress), accountCapsule3); - - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -165,9 +140,8 @@ public void testSuccess() { TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); @@ -180,9 +154,7 @@ public void testSuccess() { Assert.assertEquals(57466800, balance); Assert.assertEquals(624668 * Constant.SUN_PER_ENERGY, balance + energy * Constant.SUN_PER_ENERGY); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } @@ -204,8 +176,7 @@ public void testSuccessNoBandWidth() { new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); long bandWidth = trxCap.getSerializedSize() + Constant.MAX_RESULT_SIZE_IN_TX; - BlockCapsule blockCapsule = null; - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); trace.check(); @@ -220,9 +191,7 @@ public void testSuccessNoBandWidth() { Assert.assertEquals(0, receipt.getEnergyFee()); Assert.assertEquals(totalBalance, balance); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } } @@ -270,9 +239,8 @@ private byte[] createContract() TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); trace.check(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java index 200df06f084..a5c397e54c2 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java @@ -1,30 +1,25 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -33,40 +28,22 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j -public class BatchSendTest { +public class BatchSendTest extends BaseTest { - private static final String dbPath = "output_BatchSendTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; - private static final long TOTAL_SUPPLY = 1000_000_000L; - private static final int TRX_NUM = 10; - private static final int NUM = 1; - private static final long START_TIME = 1; - private static final long END_TIME = 2; - private static final int VOTE_SCORE = 2; - private static final String DESCRIPTION = "TRX"; - private static final String URL = "https://tron.network"; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; - private static AccountCapsule ownerCapsule; + private static final AccountCapsule ownerCapsule; static { + dbPath = "output_BatchSendTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); - repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); - repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - repository.addBalance(Hex.decode(TRANSFER_TO), 10); - repository.commit(); + ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -74,40 +51,31 @@ public class BatchSendTest { AccountType.AssetIssue); ownerCapsule.setBalance(1000_1000_1000L); + + + } + + @Before + public void before() { + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 10); + repository.commit(); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); dbManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); dbManager.getDynamicPropertiesStore().saveAllowTvmSolidity059(1); - - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** * pragma solidity ^0.5.4; - * * contract TestBatchSendTo { constructor() public payable{} - * * function depositIn() public payable{} - * - * * function batchSendTo (address payable to1 ,address payable to2 ,address payable to3, uint256 * m1,uint256 m2,uint256 m3) public { to1.send(m1 ); to2.send(m2 ); to3.send(m3 ); } - * * } */ @Test @@ -181,10 +149,9 @@ private byte[] deployTransferContract() long tokenValue = 0; long tokenId = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, repository, null); - return contractAddress; } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java index f7226bb3b3d..524c40ee8fb 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java @@ -6,16 +6,16 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; import org.tron.common.utils.StringUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.db.TransactionTrace; import org.tron.core.vm.PrecompiledContracts; import org.tron.core.vm.PrecompiledContracts.BatchValidateSign; -import stest.tron.wallet.common.client.utils.AbiUtil; + @Slf4j public class BatchValidateSignContractTest { @@ -76,7 +76,7 @@ public void staticCallTest() { Assert.assertEquals(ret.getValue(), new byte[32]); System.gc(); // force triggering full gc to avoid timeout for next test } - + @Test public void correctionTest() { contract.setConstantCall(false); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java index 91378fdcb64..600b81750da 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java @@ -1,24 +1,16 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -28,28 +20,24 @@ import org.tron.protos.Protocol.AccountType; @Slf4j +public class ChargeTest extends BaseTest { -public class ChargeTest { - - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_ChargeTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static String OWNER_ADDRESS; private long totalBalance = 100_000_000_000_000L; + static { + dbPath = "output_ChargeTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -88,11 +76,10 @@ public void testOverflow() + "3901905600608060405260358060116000396000f3006080604052600080fd00a165627a7a723058201738d" + "6aa899dc00d4e99de944eb74d30a9ba1fcae37b99dc6299d95e992ca8b40029a165627a7a72305820683901" + "37ba70dfc460810603eba8500b050ed3cd01e66f55ec07d387ec1cd2750029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 51293; // 200 * code.length() + 93 Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -108,7 +95,7 @@ public void testOverflow() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -154,11 +141,10 @@ public void testNegative() + "5600608060405260358060116000396000f3006080604052600080fd00a165627a7a72305820ef54aac72ef" + "ff56dbe894e7218d009a87368bb70338bb385db5d3dec9927bc2c0029a165627a7a723058201620679ac2ae" + "640d0a6c26e9cb4523e98eb0de8fff26975c5bb4c7fda1c98d720029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 68111; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -174,7 +160,7 @@ public void testNegative() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -189,7 +175,7 @@ public void testNegative() long expectEnergyUsageTotal3 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance @@ -197,27 +183,6 @@ public void testNegative() } - @Test - @Ignore - public void testFallback() - throws ContractExeException, ContractValidateException, ReceiptCheckErrException { - // done in EnergyWhenSendAndTransferTest.java - - } - - // contract TestCallDepth { - // - // function CallstackExploit(int256 counter) external { - // if (counter > 0) { - // this.CallstackExploit.gas(msg.gas - 2000)(counter - 1); - // } else {} - // } - // - // function Call(int256 counter) { - // this.CallstackExploit(counter); - // } - // } - @Test public void testCallDepth() throws ContractExeException, ContractValidateException, @@ -243,11 +208,10 @@ public void testCallDepth() + "152602001915050600060405180830381600087803b15801561012d57600080fd5b505af115801561014157" + "3d6000803e3d6000fd5b50505050505600a165627a7a72305820510367f4437b1af16931cacc744eb6f3102" + "d72f0c369aa795a4dc49a7f90a3e90029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 74517; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -265,8 +229,8 @@ public void testCallDepth() long expectEnergyUsageTotal2 = 27743; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -360,11 +324,10 @@ public void testCallDepthAndWidth() + "8e9050565b50505600a165627a7a72305820a9e7e1401001d6c131ebf4727fbcedede08d16416dc0447cef60" + "e0b9516c6a260029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 286450; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -382,8 +345,8 @@ public void testCallDepthAndWidth() long expectEnergyUsageTotal2 = 243698; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -428,11 +391,9 @@ public void testCreateDepthAndWidth() + "029a165627a7a7230582071d51c39c93b0aba5baeacea0b2bd5ca5342d028bb834046eca92975a3517a4c0" + "029"; - String libraryAddressPair = null; - TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 201839; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -450,24 +411,11 @@ public void testCreateDepthAndWidth() long expectEnergyUsageTotal2 = 4481164; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java index 137bb180dc0..8f9ea5c059a 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/Create2Test.java @@ -11,14 +11,20 @@ import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteArray; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; +import org.tron.common.utils.client.utils.DataWord; +import org.tron.core.Wallet; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.JsonRpcInvalidParamsException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.services.NodeInfoService; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.DataWord; + @Slf4j public class Create2Test extends VMTestBase { @@ -171,7 +177,8 @@ public void testCreate2() // trigger deployed contract String methodToTrigger = "plusOne()"; - for (int i = 1; i < 3; i++) { + long loop = 2; + for (int i = 1; i <= loop; i++) { hexInput = AbiUtil.parseMethod(methodToTrigger, Collections.emptyList()); result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), @@ -179,6 +186,22 @@ public void testCreate2() Assert.assertNull(result.getRuntime().getRuntimeError()); Assert.assertEquals(result.getRuntime().getResult().getHReturn(), new DataWord(i).getData()); } + testJsonRpc(actualContract, loop); + } + + private void testJsonRpc(byte[] actualContract, long loop) { + TronJsonRpcImpl tronJsonRpc; + NodeInfoService nodeInfoService; + nodeInfoService = context.getBean(NodeInfoService.class); + Wallet wallet = context.getBean(Wallet.class); + tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, manager); + try { + String res = + tronJsonRpc.getStorageAt(ByteArray.toHexString(actualContract), "0", "latest"); + Assert.assertEquals(loop, ByteArray.jsonHexToLong(res)); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } } /* diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java index 5fa63096b9f..aec3f2322a6 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java @@ -1,24 +1,16 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -33,15 +25,17 @@ @Slf4j -public class EnergyWhenAssertStyleTest { +public class EnergyWhenAssertStyleTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_EnergyWhenAssertStyleTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + + static { + dbPath = "output_EnergyWhenAssertStyleTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** @@ -49,11 +43,6 @@ public class EnergyWhenAssertStyleTest { */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -104,11 +93,10 @@ public void outOfIndexTest() + "25261016082019092526060916020820161014080388339019050509050600a81600a815181101515608c57" + "fe5b60209081029091010152505600a165627a7a723058201aaf6626083e32afa834a13d3365784c509d10f" + "57ce1024f88c697cf0718795e0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 39487; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -123,7 +111,7 @@ public void outOfIndexTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -159,11 +147,10 @@ public void bytesNTest() + "1e76e10781146043575b600080fd5b348015604e57600080fd5b5060556057565b005b72012345000000000" + "00000000000000000000000601460008282fe00a165627a7a72305820a1c7c81d642cc0aa11c43d63614a5b" + "3c018e4af84700af4bfde5f2efb18b55130029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 31875; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -178,7 +165,7 @@ public void bytesNTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -212,11 +199,10 @@ public void divZeroTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "b87d948d81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b60008080600afe00a" + "165627a7a7230582084ed35f2e244d6721bb5f5fcaf53d237ea050b3de84d5cc7fee74584fd2ff31f0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 27875; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -231,7 +217,7 @@ public void divZeroTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -267,11 +253,10 @@ public void shiftByNegativeTest() + "e88e362a81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b60091960008161040" + "0fe00a165627a7a7230582086c99cfe65e26909bb0fb3a2bdaf2385ad8dfff72680adab954063a4fe1d549b" + "0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 28475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -286,7 +271,7 @@ public void shiftByNegativeTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -322,11 +307,10 @@ public void enumTypeTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "5a43cddc81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b6000600afe00a1656" + "27a7a72305820b24a4d459b753723d300f56c408c6120d5ef0c7ddb166d66ccf4277a76ad83ed0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 27475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -341,7 +325,7 @@ public void enumTypeTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -376,11 +360,10 @@ public void functionPointerTest() + "e9ad8ee781146043575b600080fd5b348015604e57600080fd5b5060556057565b005b606a606660018263f" + "fffffff16565b5050565bfe00a165627a7a723058201c8982fa288ec7aad86b1d1992ecc5d08c4b22e4fe03" + "7981f91aff8bcbd900680029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 30475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -395,7 +378,7 @@ public void functionPointerTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -429,11 +412,10 @@ public void assertTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "2b813bc081146043575b600080fd5b348015604e57600080fd5b5060556057565b005bfe00a165627a7a723" + "058208ce7511bd3a946a22baaba2b4521cbf29d2481ad52887c5567e422cd89726eda0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26675; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -448,7 +430,7 @@ public void assertTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -497,11 +479,10 @@ public void systemPrecompileTest() + "fffffff868116825260208201869052825193169381830193909290918290030181855af491505015156101" + "2957600080fd5b50505600a165627a7a723058206090aa7a8ac0e45fac642652417495e81dad6f1592343bf" + "f8cfe97f61cf74e880029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 89214; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -520,7 +501,7 @@ public void systemPrecompileTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof PrecompiledContractException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -557,11 +538,10 @@ public void outOfMemTest() + "b82821015609957604080516230040080825263060080208201909252906020820163060080008038833901" + "9050506001909201919050605f565b5050505600a165627a7a723058209e5d294a7bf5133b304bc6851c749" + "cd5e1f4748230405755e6bd2e31549ae1d00029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 40487; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -576,32 +556,12 @@ public void outOfMemTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof OutOfMemoryException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - @Test - @Ignore - public void overflowTest() - throws ContractExeException, ReceiptCheckErrException, ContractValidateException { - // done in ChargeTest - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java index 5ce9729393f..2356a649e82 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java @@ -1,24 +1,16 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -29,16 +21,17 @@ import org.tron.protos.Protocol.AccountType; @Slf4j +public class EnergyWhenRequireStyleTest extends BaseTest { -public class EnergyWhenRequireStyleTest { - - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_EnergyWhenRequireStyleTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + + static { + dbPath = "output_EnergyWhenRequireStyleTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** @@ -46,11 +39,6 @@ public class EnergyWhenRequireStyleTest { */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -100,11 +88,10 @@ public void throwTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "50bff6bf81146043575b600080fd5b348015604e57600080fd5b506055603e565b0000a165627a7a7230582" + "0f51282c5910e3ff1b5f2e9509f3cf23c7035027aae1947ab46e5a9252fb061eb0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26275; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -120,8 +107,8 @@ public void throwTest() long expectEnergyUsageTotal2 = 124; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -153,11 +140,10 @@ public void requireTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "357815c481146043575b600080fd5b348015604e57600080fd5b506055603e565b0000a165627a7a7230582" + "054141931bcc37d4f266815f02d2fb113f5af20825cbce45d3b0f2fe90ac0145d0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26275; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -173,8 +159,8 @@ public void requireTest() long expectEnergyUsageTotal2 = 124; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -217,11 +203,10 @@ public void thisFunctionViaMessageCallTest() + "000000000000000028152600401600060405180830381600088803b15801560db57600080fd5b5087f11580" + "1560ee573d6000803e3d6000fd5b50505050505600a165627a7a7230582087d830c44fb566498789b212e3d" + "0374f7a7589a2efdda11b3a4c03051b57891a0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 57905; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -237,8 +222,8 @@ public void thisFunctionViaMessageCallTest() long expectEnergyUsageTotal2 = 5339; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -294,11 +279,10 @@ public void thatFunctionViaMessageCallTest() + "0006000350416632b813bc081146043575b600080fd5b348015604e57600080fd5b5060556057565b005bfe" + "00a165627a7a72305820c02c76575c2a0ada80c3f6db47f885cece6c254d1e7c79eb6ddc1c1d4e70ebae002" + "9a165627a7a72305820cf879e62f738b44636adf61bd4b2fb38c10f027d2a4484d58baf44a06dc97bd90029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 97341; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -314,8 +298,8 @@ public void thatFunctionViaMessageCallTest() long expectEnergyUsageTotal2 = 64125; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -356,11 +340,10 @@ public void newContractTest1() + "10066610087565b604051809103906000f080158015610082573d6000803e3d6000fd5b505050565b604051" + "6013806100978339019056006080604052348015600f57600080fd5b50fe00a165627a7a72305820685ff8f" + "74890f671deb4d3881a4b72ab0daac2ab0d36112e1ebdf98a43ac4d940029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 42687; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -377,7 +360,7 @@ public void newContractTest1() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); // todo: revert should be true!! see later - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof OutOfEnergyException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -433,22 +416,21 @@ public void receiveTrxWithoutPayableTest() + "4052348015600f57600080fd5b500000a165627a7a72305820a82006ee5ac783bcea7085501eaed33360b31" + "20278f1f39e611afedc9f4a693b0029a165627a7a72305820a50d9536f182fb6aefc737fdc3a675630e75a0" + "8de88deb6b1bee6d4b6dff04730029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 42; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - expectEnergyUsageTotal * 100); result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, 0, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); byte[] contractAddress = result.getContractAddress(); long expectEnergyUsageTotal2 = 100341; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); @@ -462,21 +444,13 @@ public void receiveTrxWithoutPayableTest() long expectEnergyUsageTotal3 = 51833; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2 + expectEnergyUsageTotal3) * 100); } - @Test - @Ignore - public void transferTest() - throws ContractExeException, ReceiptCheckErrException, ContractValidateException { - // done in EnergyWhenSendAndTransferTest - - } - // pragma solidity ^0.4.16; // // contract TestRevertContract { @@ -512,11 +486,10 @@ public void revertTest() + "6312065fe08114604d578063a26388bb146071575b600080fd5b348015605857600080fd5b50605f6085565" + "b60408051918252519081900360200190f35b348015607c57600080fd5b5060836048565b005b3031905600" + "a165627a7a7230582059cab3a7a5851a7852c728ec8729456a04dc022674976f3f26bfd51491dbf1080029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 36481; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -532,31 +505,11 @@ public void revertTest() long expectEnergyUsageTotal2 = 146; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - @Test - @Ignore - public void reach64CallDepth() { - // done in ChargeTest - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java index b834f953eb4..40af27612df 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java @@ -1,23 +1,16 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -27,26 +20,23 @@ import org.tron.protos.Protocol.AccountType; @Slf4j -public class EnergyWhenSendAndTransferTest { +public class EnergyWhenSendAndTransferTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_EnergyWhenSendAndTransferTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + dbPath = "output_EnergyWhenSendAndTransferTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -124,7 +114,7 @@ public void callValueTest() long expectEnergyUsageTotal3 = 9459; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2 + expectEnergyUsageTotal3) * 100); } @@ -189,8 +179,8 @@ public void sendTest() long expectEnergyUsageTotal2 = 7025; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertNull(result.getRuntime().getResult().getException()); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -224,8 +214,8 @@ public void transferTest() long expectEnergyUsageTotal2 = 7030; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); + Assert.assertNull(result.getRuntime().getResult().getException()); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -260,11 +250,10 @@ public TVMTestResult deployCallValueTestContract(long value, long feeLimit, + "b602a90565b6000805b600a81101560945760008181526020819052604090208190556001016074565b5090" + "5600a165627a7a723058205ded543feb546472be4e116e713a2d46b8dafc823ca31256e67a1be92a6752730" + "029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); } public TVMTestResult deploySendAndTransferTestContract(long value, long feeLimit, @@ -294,25 +283,9 @@ public TVMTestResult deploySendAndTransferTestContract(long value, long feeLimit + "2600160008181526020527fada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d" + "550000a165627a7a7230582029b27c10c1568d590fa66bc0b7d42537a314c78d028f59a188fa411f7fc15c4" + "f0029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); } - - /** - * Release resources. - */ - @After - public void destroy() { - context.destroy(); - Args.clearParam(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.warn("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java index 73b51c803f8..c2dc1d524ad 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java @@ -1,23 +1,16 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -29,28 +22,24 @@ import org.tron.protos.Protocol.AccountType; @Slf4j -public class EnergyWhenTimeoutStyleTest { +public class EnergyWhenTimeoutStyleTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_CPUTimeTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + dbPath = "output_CPUTimeTest"; + Args.setParam(new String[]{"--output-directory", dbPath}, + Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, - Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -109,7 +98,6 @@ public void endlessLoopTest() /* =================================== CALL setVote(uint256) =============================== */ String params = "0000000000000000000000000000000000000000000000000000000000000003"; byte[] triggerData = TvmTestUtils.parseAbi("setVote(uint256)", params); - boolean haveException = false; result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), contractAddress, triggerData, value, feeLimit, dbManager, null); @@ -144,27 +132,11 @@ public TVMTestResult deployEndlessLoopContract(long value, long feeLimit, + "60011560cb576001600080828254019250508190555060b1565b505600a165627a7a72305820290a38c9bbaf" + "ccaf6c7f752ab56d229e354da767efb72715ee9fdb653b9f4b6c0029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, + feeLimit, consumeUserResourcePercent, null, dbManager, null); } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java index 8acc8ed494b..d8c8a23a8ee 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java @@ -9,12 +9,12 @@ import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class ExtCodeHashTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java index ae655e6eb24..600000e6535 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java @@ -26,6 +26,7 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -46,7 +47,6 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class FreezeTest { 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 441aee15676..78096564e48 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 @@ -30,6 +30,7 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -55,7 +56,6 @@ import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Result.contractResult; import org.tron.protos.contract.Common; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class FreezeV2Test { @@ -1060,4 +1060,4 @@ public void destroy() { logger.error("Release resources failure."); } } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java index d5d6a18b031..540a30a240f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java @@ -9,6 +9,7 @@ import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -16,7 +17,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class IsContractTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java index e95eaf46189..3cec683ed63 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java @@ -9,6 +9,7 @@ import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -22,7 +23,6 @@ import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class IsSRCandidateTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java index f9f586b87a6..965c7e0ce1a 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/OperationsTest.java @@ -13,17 +13,15 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.util.StringUtils; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.InternalTransaction; import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.StoreFactory; +import org.tron.core.vm.EnergyCost; import org.tron.core.vm.JumpTable; import org.tron.core.vm.Op; import org.tron.core.vm.Operation; @@ -36,22 +34,16 @@ import org.tron.protos.Protocol; @Slf4j -public class OperationsTest { +public class OperationsTest extends BaseTest { private ProgramInvokeMockImpl invoke; private Program program; - private final JumpTable jumpTable = OperationRegistry.newTronV10OperationSet(); - private static ChainBaseManager chainBaseManager; - private static String dbPath; - private static TronApplicationContext context; + private final JumpTable jumpTable = OperationRegistry.getTable(); @BeforeClass public static void init() { - dbPath = "output_" + OperationsTest.class.getName(); + dbPath = "output_operations_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - Manager manager = context.getBean(Manager.class); - chainBaseManager = manager.getChainBaseManager(); CommonParameter.getInstance().setDebug(true); VMConfig.initAllowTvmTransferTrc10(1); VMConfig.initAllowTvmConstantinople(1); @@ -66,12 +58,7 @@ public static void destroy() { ConfigLoader.disable = false; VMConfig.initVmHardFork(false); Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } + FileUtil.deleteDir(new File(dbPath)); VMConfig.initAllowTvmTransferTrc10(0); VMConfig.initAllowTvmConstantinople(0); VMConfig.initAllowTvmSolidity059(0); @@ -196,7 +183,7 @@ public void testArithmeticOperations() throws ContractValidateException { // test MULMOD op = new byte[]{0x60, 0x02, 0x60, 0x01, 0x60, 0x01, 0x09}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(17, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); @@ -254,7 +241,7 @@ public void testLogicAndComparisonOperations() throws ContractValidateException // test EQ = 0X14 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0X14}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); @@ -275,7 +262,7 @@ public void testLogicAndComparisonOperations() throws ContractValidateException // test OR = 0x17 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x17}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x03), program.getStack().pop()); @@ -303,7 +290,7 @@ public void testLogicAndComparisonOperations() throws ContractValidateException // test SHL = 0x1b op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x1b}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x02), program.getStack().pop()); @@ -342,7 +329,7 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // test ADDRESS = 0x30 op = new byte[]{0x30}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertArrayEquals(invoke.getContractAddress().getLast20Bytes(), @@ -520,7 +507,7 @@ public void testMemoryStorageAndFlowOperations() throws ContractValidateExceptio // MSTORE8 = 0x53 op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x53}; - program = new Program(op, op, invoke, interTrx);; + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed(), 41); Assert.assertEquals(32, program.getMemSize()); @@ -862,6 +849,25 @@ public void testComplexOperations() throws ContractValidateException { } + @Test + public void testPush0() throws ContractValidateException { + VMConfig.initAllowTvmShangHai(1); + + invoke = new ProgramInvokeMockImpl(); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + byte[] op = new byte[1]; + op[0] = Op.PUSH0; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(EnergyCost.getBaseTierCost(null), program.getResult().getEnergyUsed()); + Assert.assertEquals(DataWord.ZERO(), program.getStack().pop()); + + VMConfig.initAllowTvmShangHai(0); + } + private void testOperations(Program program) { try { while (!program.isStopped()) { @@ -897,10 +903,10 @@ private void testOperations(Program program) { } catch (Program.JVMStackOverFlowException | Program.OutOfTimeException e) { throw e; } catch (RuntimeException e) { - if (StringUtils.isEmpty(e.getMessage())) { - program.setRuntimeFailure(new RuntimeException("Unknown Exception")); - } else { + if (StringUtils.hasLength(e.getMessage())) { program.setRuntimeFailure(e); + } else { + program.setRuntimeFailure(new RuntimeException("Unknown Exception")); } } catch (StackOverflowError soe) { logger.info("\n !!! StackOverflowError: update your java run command with -Xss !!!\n", soe); @@ -937,10 +943,10 @@ private void testSingleOperation(Program program) { } catch (Program.JVMStackOverFlowException | Program.OutOfTimeException e) { throw e; } catch (RuntimeException e) { - if (StringUtils.isEmpty(e.getMessage())) { - program.setRuntimeFailure(new RuntimeException("Unknown Exception")); - } else { + if (StringUtils.hasLength(e.getMessage())) { program.setRuntimeFailure(e); + } else { + program.setRuntimeFailure(new RuntimeException("Unknown Exception")); } } catch (StackOverflowError soe) { logger.info("\n !!! StackOverflowError: update your java run command with -Xss !!!\n", soe); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java index 492f9540df2..b4365f02338 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java @@ -6,27 +6,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; - import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.ProgramResult; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -37,9 +30,7 @@ import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -56,21 +47,17 @@ import org.tron.protos.contract.Common; @Slf4j -public class PrecompiledContractsTest { +public class PrecompiledContractsTest extends BaseTest { // common private static final DataWord voteContractAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010001"); - private static final DataWord withdrawBalanceAddr = new DataWord( - "0000000000000000000000000000000000000000000000000000000000010004"); private static final DataWord proposalApproveAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010005"); private static final DataWord proposalCreateAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010006"); private static final DataWord proposalDeleteAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010007"); - private static final DataWord convertFromTronBytesAddressAddr = new DataWord( - "0000000000000000000000000000000000000000000000000000000000010008"); private static final DataWord convertFromTronBase58AddressAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010009"); @@ -108,7 +95,6 @@ public class PrecompiledContractsTest { private static final DataWord totalAcquiredResourceAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000001000015"); - private static final String dbPath = "output_PrecompiledContracts_test"; private static final String ACCOUNT_NAME = "account"; private static final String OWNER_ADDRESS; private static final String WITNESS_NAME = "witness"; @@ -117,44 +103,16 @@ public class PrecompiledContractsTest { private static final String URL = "https://tron.network"; // withdraw private static final long initBalance = 10_000_000_000L; - private static final long allowance = 32_000_000L; private static final long latestTimestamp = 1_000_000L; - private static TronApplicationContext context; - private static Application appT; - private static Manager dbManager; static { + dbPath = "output_PrecompiledContracts_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + WITNESS_ADDRESS_BASE; } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -459,7 +417,6 @@ public void delegatableResourceTest() { // with usage. byte[] TOTAL_ENERGY_CURRENT_LIMIT = "TOTAL_ENERGY_CURRENT_LIMIT".getBytes(); - byte[] TOTAL_ENERGY_WEIGHT = "TOTAL_ENERGY_WEIGHT".getBytes(); long energyLimit = 1_000_000_000_000L; tempRepository.getDynamicPropertiesStore().put(TOTAL_ENERGY_CURRENT_LIMIT, @@ -1170,10 +1127,6 @@ public void totalAcquiredResourceTest() { Assert.assertEquals(0, ByteArray.toLong(res.getRight())); } - @Test - public void convertFromTronBytesAddressNativeTest() { - } - //@Test public void convertFromTronBase58AddressNative() { // 27WnTihwXsqCqpiNedWvtKCZHsLjDt4Hfmf TestNet address diff --git a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java index 8be1ebf88df..d97be9581b7 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java @@ -1,30 +1,29 @@ package org.tron.common.runtime.vm; +import static org.junit.Assert.assertNotNull; + import com.google.protobuf.ByteString; -import java.io.File; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.client.WalletClient; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; import org.tron.common.zksnark.LibrustzcashParam; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.vm.PrecompiledContracts.MerkleHash; @@ -42,55 +41,30 @@ import org.tron.core.zen.note.Note; import org.tron.keystore.Wallet; import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.WalletClient; @Slf4j -public class PrecompiledContractsVerifyProofTest { +public class PrecompiledContractsVerifyProofTest extends BaseTest { - private static final String dbPath = "output_PrecompiledContracts_VerifyProof_test"; private static final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; - private static final byte[] SHIELDED_CONTRACT_ADDRESS; + private static byte[] SHIELDED_CONTRACT_ADDRESS; private static final String PUBLIC_TO_ADDRESS_STR = "TBaBXpRAeBhs75TZT751LwyhrcR25XeUot"; - private static final byte[] PUBLIC_TO_ADDRESS; - private static final byte[] DEFAULT_OVK; - private static TronApplicationContext context; - private static Manager dbManager; - - static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-test.conf"); - context = new TronApplicationContext(DefaultConfig.class); - DEFAULT_OVK = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); - PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR); - FullNodeHttpApiService.librustzcashInitZksnarkParams(); - } + private static byte[] PUBLIC_TO_ADDRESS; + private static byte[] DEFAULT_OVK; VerifyMintProof mintContract = new VerifyMintProof(); VerifyTransferProof transferContract = new VerifyTransferProof(); VerifyBurnProof burnContract = new VerifyBurnProof(); MerkleHash merkleHash = new MerkleHash(); - /** - * Init data. - */ @BeforeClass public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + dbPath = "output_PrecompiledContracts_VerifyProof_test"; + Args.setParam(new String[]{"--output-directory", dbPath}, "config-test.conf"); + DEFAULT_OVK = ByteArray + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR); + FullNodeHttpApiService.librustzcashInitZksnarkParams(); } @Test @@ -110,7 +84,8 @@ public void verifyMintProofCorrect() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -152,9 +127,10 @@ public void verifyTransferProofCorrect() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -242,14 +218,16 @@ public void verifyTransferProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -308,8 +286,8 @@ public void verifyTransfer1v1ProofCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -358,7 +336,8 @@ public void verifyTransfer1v1ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 100, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -413,8 +392,8 @@ public void verifyBurnWithCmCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -464,7 +443,8 @@ public void verifyBurnWithCmCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -519,8 +499,8 @@ public void verifyTransfer1v2ProofCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -569,14 +549,16 @@ public void verifyTransfer1v2ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -637,9 +619,10 @@ public void verifyTransfer2v1ProofCorrect() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -727,7 +710,8 @@ public void verifyTransfer2v1ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 100, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -780,12 +764,11 @@ public void verifyBurnProofCorrect() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -861,7 +844,8 @@ public void merkleHashCorrectTest() throws ZksnarkException { IncomingViewingKey ivk = fvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress paymentAddress = ivk.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = ivk.address(DiversifierT.random()).orElse(null); + assertNotNull(paymentAddress); Note note = new Note(paymentAddress.getD(), paymentAddress.getPkD(), randomLong(), rcm, new byte[512]); byte[] node = note.cm(); @@ -898,8 +882,8 @@ public void verifyBurnWithCmWrong() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -949,7 +933,7 @@ public void verifyBurnWithCmWrong() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1019,7 +1003,7 @@ public void verifyMintWrongDataLength() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1045,9 +1029,10 @@ public void verifyTransferWrongDataLength() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1082,14 +1067,14 @@ public void verifyTransferWrongDataLength() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1110,8 +1095,8 @@ public void verifyBurnWrongDataLength() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.BURN); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1155,7 +1140,8 @@ public void verifyMintWrongLeafcount() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1181,9 +1167,10 @@ public void verifyTransferWrongLeafcount() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); for (long leafCount : leafCountList) { ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); @@ -1218,14 +1205,14 @@ public void verifyTransferWrongLeafcount() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1249,8 +1236,8 @@ public void verifyTransferDuplicateNf() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1275,14 +1262,14 @@ public void verifyTransferDuplicateNf() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1307,9 +1294,10 @@ public void verifyTransferDuplicateReceiveNotes() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1344,7 +1332,8 @@ public void verifyTransferDuplicateReceiveNotes() throws ZksnarkException { SpendingKey receiveSk = SpendingKey.random(); FullViewingKey receiveFvk = receiveSk.fullViewingKey(); IncomingViewingKey receiveIvk = receiveFvk.inViewingKey(); - PaymentAddress receivePaymentAddress = receiveIvk.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress = receiveIvk.address(new DiversifierT()).orElse(null); + assertNotNull(receivePaymentAddress); byte[] r = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(r); builder.addOutput(senderOvk, receivePaymentAddress.getD(), receivePaymentAddress.getPkD(), @@ -1376,7 +1365,8 @@ public void verifyMintWrongValue() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1394,12 +1384,11 @@ public void verifyBurnWrongValue() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.BURN); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1443,7 +1432,8 @@ public void verifyMintProofWrongCM() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1473,7 +1463,8 @@ public void verifyMintProofWrongCV() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1502,7 +1493,8 @@ public void verifyMintProofWrongEpk() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1531,7 +1523,8 @@ public void verifyMintProofWrongProof() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1560,7 +1553,8 @@ public void verifyMintProofWrongBindingSignature() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1589,7 +1583,8 @@ public void verifyMintProofWrongHash() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1619,9 +1614,10 @@ public void verifyTransferProofWrongNf() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1707,14 +1703,16 @@ public void verifyTransferProofWrongNf() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1745,9 +1743,10 @@ public void verifyTransferProofWrongRoot() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1833,14 +1832,16 @@ public void verifyTransferProofWrongRoot() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1872,9 +1873,10 @@ public void verifyTransferProofWrongSpendCV() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1960,14 +1962,16 @@ public void verifyTransferProofWrongSpendCV() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1998,9 +2002,10 @@ public void verifyTransferProofWrongRk() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2086,14 +2091,16 @@ public void verifyTransferProofWrongRk() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2124,9 +2131,10 @@ public void verifyTransferProofWrongSpendProof() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2212,14 +2220,16 @@ public void verifyTransferProofWrongSpendProof() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2250,9 +2260,10 @@ public void verifyTransferProofWrongCm() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2338,14 +2349,16 @@ public void verifyTransferProofWrongCm() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2376,9 +2389,10 @@ public void verifyTransferProofWrongReceiveCV() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2464,14 +2478,16 @@ public void verifyTransferProofWrongReceiveCV() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2502,9 +2518,10 @@ public void verifyTransferProofWrongEpk() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2590,14 +2607,16 @@ public void verifyTransferProofWrongEpk() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2628,9 +2647,10 @@ public void verifyTransferProofWrongReceiveProof() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2716,14 +2736,16 @@ public void verifyTransferProofWrongReceiveProof() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2754,9 +2776,10 @@ public void verifyTransferProofWrongBindingSignature() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2842,14 +2865,16 @@ public void verifyTransferProofWrongBindingSignature() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2880,9 +2905,10 @@ public void verifyTransferProofWrongHash() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2968,14 +2994,16 @@ public void verifyTransferProofWrongHash() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -3001,12 +3029,11 @@ public void verifyBurnWrongNF() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3072,12 +3099,11 @@ public void verifyBurnWrongRoot() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3144,12 +3170,11 @@ public void verifyBurnWrongCV() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3215,12 +3240,11 @@ public void verifyBurnWrongRk() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3286,12 +3310,11 @@ public void verifyBurnWrongProof() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3357,12 +3380,11 @@ public void verifyBurnWrongAuthoritySingature() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3428,12 +3450,11 @@ public void verifyBurnWrongBindingSingature() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3499,12 +3520,11 @@ public void verifyBurnWrongHash() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3560,21 +3580,19 @@ public void verifyBurnWrongHash() throws ZksnarkException { private Pair verifyTransfer(byte[] input) { transferContract.getEnergyForData(input); transferContract.setVmShouldEndInUs(System.nanoTime() / 1000 + 50 * 1000); - Pair ret = transferContract.execute(input); - return ret; + return transferContract.execute(input); } private IncrementalMerkleVoucherContainer addSimpleMerkleVoucherContainer( IncrementalMerkleTreeContainer tree, byte[][] cm) throws ZksnarkException { - for (int i = 0; i < cm.length; i++) { + for (byte[] bytes : cm) { PedersenHashCapsule compressCapsule = new PedersenHashCapsule(); - compressCapsule.setContent(ByteString.copyFrom(cm[i])); + compressCapsule.setContent(ByteString.copyFrom(bytes)); ShieldContract.PedersenHash a = compressCapsule.getInstance(); tree.append(a); } - IncrementalMerkleVoucherContainer voucher = tree.toVoucher(); - return voucher; + return tree.toVoucher(); } private byte[] decodePath(byte[] encodedPath) { @@ -3677,24 +3695,6 @@ private byte[] abiEncodeForMintWrongProof(ShieldedTRC20Parameters params, long v return mergedBytes; } - private byte[] abiEncodeForMintWrongBindingSignature(ShieldedTRC20Parameters params, long value, - byte[] frontier, long leafCount) { - byte[] mergedBytes; - ShieldContract.ReceiveDescription revDesc = params.getReceiveDescription(0); - mergedBytes = ByteUtil.merge( - revDesc.getNoteCommitment().toByteArray(), - revDesc.getValueCommitment().toByteArray(), - revDesc.getEpk().toByteArray(), - revDesc.getZkproof().toByteArray(), - Wallet.generateRandomBytes(64), - longTo32Bytes(value), - params.getMessageHash().toByteArray(), - frontier, - longTo32Bytes(leafCount) - ); - return mergedBytes; - } - private byte[] abiEncodeForMintWrongHash(ShieldedTRC20Parameters params, long value, byte[] frontier, long leafCount) { byte[] mergedBytes; @@ -4505,7 +4505,7 @@ private byte[] longTo32Bytes(long value) { } private long randomLong() { - return (long) Math.round(Math.random() * Long.MAX_VALUE / 2); + return Math.round(Math.random() * Long.MAX_VALUE / 2); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java b/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java index 6323ef4aa40..390b1396337 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java @@ -1,27 +1,22 @@ package org.tron.common.runtime.vm; -import java.io.File; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.WalletUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -33,20 +28,19 @@ import org.tron.protos.Protocol.Transaction; @Slf4j -public class RepositoryTest { +public class RepositoryTest extends BaseTest { - private Manager manager; - private TronApplicationContext context; - private String dbPath = "output_DepostitTest"; - private String OWNER_ADDRESS; + private static final String OWNER_ADDRESS; private Repository rootRepository; + + static { + dbPath = "output_DepostitTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - manager = context.getBean(Manager.class); rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); rootRepository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); rootRepository.addBalance(Hex.decode(OWNER_ADDRESS), 30000000000000L); @@ -102,9 +96,9 @@ public void loopCallTest() VMIllegalException, ContractValidateException { byte[] stats = new byte[27]; Arrays.fill(stats, (byte) 1); - this.manager.getDynamicPropertiesStore() + this.dbManager.getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); - this.manager.getDynamicPropertiesStore() + this.dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderNumber(CommonParameter.getInstance() .getBlockNumForEnergyLimit() + 1); @@ -206,7 +200,7 @@ public void loopCallTest() .parseAbi("callBcallARevert(address,uint256,uint256)", params1); TVMTestResult result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); + aAddress, triggerData, 0, fee, dbManager, null); Assert.assertNull(result.getRuntime().getRuntimeError()); // check result @@ -216,10 +210,10 @@ public void loopCallTest() TVMTestResult checkN1 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); + aAddress, checkN1Data, 0, fee, dbManager, null); TVMTestResult checkN2 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); + aAddress, checkN2Data, 0, fee, dbManager, null); System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); @@ -238,14 +232,14 @@ public void loopCallTest() triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); + aAddress, triggerData, 0, fee, dbManager, null); Assert.assertNull(result.getRuntime().getRuntimeError()); checkN1 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); + aAddress, checkN1Data, 0, fee, dbManager, null); checkN2 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); + aAddress, checkN2Data, 0, fee, dbManager, null); System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), @@ -262,7 +256,7 @@ public void loopCallTestOldVersion() VMIllegalException, ContractValidateException { byte[] stats = new byte[27]; Arrays.fill(stats, (byte) 0); - this.manager.getDynamicPropertiesStore() + this.dbManager.getDynamicPropertiesStore() .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); String contractA = "A"; @@ -360,7 +354,7 @@ public void loopCallTestOldVersion() .parseAbi("callBcallARevert(address,uint256,uint256)", params1); TVMTestResult result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); + aAddress, triggerData, 0, fee, dbManager, null); Assert.assertNull(result.getRuntime().getRuntimeError()); // check result @@ -370,10 +364,10 @@ public void loopCallTestOldVersion() TVMTestResult checkN1 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); + aAddress, checkN1Data, 0, fee, dbManager, null); TVMTestResult checkN2 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); + aAddress, checkN2Data, 0, fee, dbManager, null); System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); @@ -392,14 +386,14 @@ public void loopCallTestOldVersion() triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); + aAddress, triggerData, 0, fee, dbManager, null); Assert.assertNull(result.getRuntime().getRuntimeError()); checkN1 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); + aAddress, checkN1Data, 0, fee, dbManager, null); checkN2 = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); + aAddress, checkN2Data, 0, fee, dbManager, null); System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), @@ -409,17 +403,4 @@ public void loopCallTestOldVersion() new DataWord(1000).getData()); CommonParameter.setENERGY_LIMIT_HARD_FORK(false); } - - - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java index 1711f8441e6..b9fa24712c9 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java @@ -10,6 +10,7 @@ import org.tron.common.utils.Base58; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.capsule.BlockCapsule; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -25,7 +26,6 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class RewardBalanceTest extends VMTestBase { diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java index c5ac42e93ce..2c04b302c49 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java @@ -1,24 +1,17 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -29,27 +22,24 @@ @Slf4j @Ignore -public class TimeBenchmarkTest { +public class TimeBenchmarkTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private RepositoryImpl repository; - private String dbPath = "output_TimeBenchmarkTest"; - private String OWNER_ADDRESS; - private Application AppT; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + dbPath = "output_TimeBenchmarkTest"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); @@ -137,23 +127,9 @@ public void timeBenchmark() long expectEnergyUsageTotal2 = 110; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java index 51d8e8dafae..8a3bbbbeede 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java @@ -12,6 +12,7 @@ import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -20,7 +21,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import stest.tron.wallet.common.client.utils.AbiUtil; public class TransferFailedEnergyTest extends VMTestBase { /* diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java index aa6fccecc7a..13f01847c81 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java @@ -1,23 +1,20 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -26,9 +23,7 @@ import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -40,12 +35,10 @@ import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j -public class TransferToAccountTest { +public class TransferToAccountTest extends BaseTest { - private static final String dbPath = "output_TransferToAccountTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static final long TOTAL_SUPPLY = 1000_000_000L; @@ -57,21 +50,18 @@ public class TransferToAccountTest { private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; private static Runtime runtime; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; private static AccountCapsule ownerCapsule; static { + dbPath = "output_TransferToAccountTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); + } + + @Before + public void before() { repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); repository.addBalance(Hex.decode(TRANSFER_TO), 10); @@ -85,20 +75,6 @@ public class TransferToAccountTest { ownerCapsule.setBalance(1000_1000_1000L); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - private long createAsset(String tokenName) { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); chainBaseManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); @@ -250,7 +226,6 @@ public void TransferTokenTest() // 9.Test transferToken Big Amount selectorStr = "transferTokenTo(address,trcToken,uint256)"; - ecKey = new ECKey(Utils.getRandom()); String params = "000000000000000000000000548794500882809695a8a687866e76d4271a1abc" + Hex.toHexString(new DataWord(id).getData()) + "0000000000000000000000000000000011111111111111111111111111111111"; @@ -318,10 +293,9 @@ private byte[] deployTransferContract(long id) long tokenValue = 100; long tokenId = id; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, repository, null); - return contractAddress; } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java index 754c03118a5..bc9a60a9704 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java @@ -1,26 +1,20 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -32,9 +26,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class TransferTokenTest { +public class TransferTokenTest extends BaseTest { - private static final String dbPath = "output_TransferTokenTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static final long TOTAL_SUPPLY = 1000_000_000L; @@ -46,20 +39,19 @@ public class TransferTokenTest { private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; private static RepositoryImpl repository; private static AccountCapsule ownerCapsule; static { + dbPath = "output_TransferTokenTest"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); + } + + @Before + public void before() { repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); repository.addBalance(Hex.decode(TRANSFER_TO), 10); @@ -73,20 +65,6 @@ public class TransferTokenTest { ownerCapsule.setBalance(1000_1000_1000L); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - private long createAsset(String tokenName) { dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); @@ -116,13 +94,11 @@ private long createAsset(String tokenName) { /** * pragma solidity ^0.4.24; - * * contract tokenTest{ constructor() public payable{} // positive case function * TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ * toAddress.transferToken(amount,id); } function suicide(address toAddress) payable public{ * selfdestruct(toAddress); } function get(trcToken trc) public payable returns(uint256){ return * address(this).tokenBalance(trc); } } - * * 1. deploy 2. trigger and internal transaction 3. suicide (all token) */ @Test diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java index 4ce516cd11f..e6ef013bd85 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java @@ -1,75 +1,54 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; +import org.junit.Before; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.StringUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.store.StoreFactory; import org.tron.core.vm.PrecompiledContracts.ValidateMultiSign; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; + @Slf4j -public class ValidateMultiSignContractTest { +public class ValidateMultiSignContractTest extends BaseTest { - private static final String dbPath = "output_ValidateMultiSignContract_test"; private static final String METHOD_SIGN = "validatemultisign(address,uint256,bytes32,bytes[])"; private static final byte[] longData; - private static TronApplicationContext context; - private static Application appT; - private static Manager dbManager; static { + dbPath = "output_ValidateMultiSignContract_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); - dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); - longData = new byte[1000000]; Arrays.fill(longData, (byte) 2); } ValidateMultiSign contract = new ValidateMultiSign(); - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + @Before + public void before() { + dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); + dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); } @Test @@ -116,7 +95,8 @@ public void testDifferentCase() { .build(); toAccount - .updatePermissions(toAccount.getPermissionById(0), null, Arrays.asList(activePermission)); + .updatePermissions(toAccount.getPermissionById(0), null, + Collections.singletonList(activePermission)); dbManager.getAccountStore().put(key.getAddress(), toAccount); //generate data diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java index 9622c8a1b25..22a33993589 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java @@ -30,6 +30,8 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; +import org.tron.common.utils.client.utils.DataWord; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -47,8 +49,6 @@ import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.DataWord; @Slf4j public class VoteTest { diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java index e693b90c3fa..eed995f12b5 100644 --- a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java +++ b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java @@ -40,6 +40,7 @@ import org.junit.Test; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; import org.tron.core.config.args.Args; import org.tron.core.db2.common.WrappedByteArray; @@ -86,7 +87,7 @@ public void initDb() { @Test public void testPutGet() { dataSourceTest.resetDb(); - String key1 = "2c0937534dd1b3832d05d865e8e6f2bf23218300b33a992740d45ccab7d4f519"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSourceTest.initDB(); String value1 = "50000"; @@ -115,9 +116,9 @@ public void testupdateByBatchInner() { Args.getInstance().getOutputDirectory(), "test_updateByBatch"); dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); String value1 = "50000"; - String key2 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757351"; + String key2 = PublicMethod.getRandomPrivateKey(); String value2 = "10000"; Map rows = new HashMap<>(); @@ -137,7 +138,7 @@ public void testdeleteData() { LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( Args.getInstance().getOutputDirectory(), "test_delete"); dataSource.initDB(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSource.deleteData(key); byte[] value = dataSource.getData(key); @@ -153,14 +154,14 @@ public void testallKeys() { dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757321"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); String value1 = "50000"; byte[] value = value1.getBytes(); dataSource.putData(key, value); - String key3 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757091"; + String key3 = PublicMethod.getRandomPrivateKey(); byte[] key2 = key3.getBytes(); String value3 = "30000"; @@ -331,4 +332,4 @@ public void prefixQueryTest() { dataSource.resetDb(); dataSource.closeDB(); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java index 1b261fd8b98..f0ceb7fcac4 100644 --- a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java +++ b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java @@ -25,6 +25,7 @@ import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.config.args.Args; import org.tron.core.db2.common.WrappedByteArray; @@ -76,7 +77,7 @@ public static void initDb() { @Test public void testPutGet() { dataSourceTest.resetDb(); - String key1 = "2c0937534dd1b3832d05d865e8e6f2bf23218300b33a992740d45ccab7d4f519"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSourceTest.initDB(); String value1 = "50000"; @@ -105,9 +106,9 @@ public void testupdateByBatchInner() { Args.getInstance().getOutputDirectory(), "test_updateByBatch"); dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); String value1 = "50000"; - String key2 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757351"; + String key2 = PublicMethod.getRandomPrivateKey(); String value2 = "10000"; Map rows = new HashMap<>(); @@ -127,7 +128,7 @@ public void testdeleteData() { RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( Args.getInstance().getOutputDirectory(), "test_delete"); dataSource.initDB(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSource.deleteData(key); byte[] value = dataSource.getData(key); @@ -143,14 +144,14 @@ public void testallKeys() { dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757321"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); String value1 = "50000"; byte[] value = value1.getBytes(); dataSource.putData(key, value); - String key3 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757091"; + String key3 = PublicMethod.getRandomPrivateKey(); byte[] key2 = key3.getBytes(); String value3 = "30000"; diff --git a/framework/src/test/java/org/tron/common/utils/PublicMethod.java b/framework/src/test/java/org/tron/common/utils/PublicMethod.java index b61ea6c8c4d..63feab160d4 100644 --- a/framework/src/test/java/org/tron/common/utils/PublicMethod.java +++ b/framework/src/test/java/org/tron/common/utils/PublicMethod.java @@ -1,17 +1,240 @@ package org.tron.common.utils; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; import com.google.protobuf.ByteString; +import java.io.IOException; import java.math.BigInteger; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Objects; +import java.util.Random; + +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; + import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.common.crypto.ECKey; +import org.tron.common.crypto.sm2.SM2; +import org.tron.common.crypto.sm2.SM2Signer; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.core.Wallet; import org.tron.protos.Protocol; import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.utils.TransactionUtils; +import org.tron.protos.contract.SmartContractOuterClass; +@Slf4j public class PublicMethod { + public static ECKey getRandomECKey(String privateKey) { + BigInteger priK = new BigInteger(privateKey, 16); + return ECKey.fromPrivate(priK); + } + + public static String getRandomPrivateKey() { + return Hex.toHexString(Objects + .requireNonNull(new ECKey(Utils.getRandom()).getPrivKeyBytes())); + } + + public static String getHexAddressByPrivateKey(String privateKey) { + return ByteArray.toHexString(getAddressByteByPrivateKey(privateKey)); + } + + public static byte[] getAddressByteByPrivateKey(String privateKey) { + return getRandomECKey(privateKey).getAddress(); + } + + public static String getPublicByPrivateKey(String privateKey) { + return Hex.toHexString(getRandomECKey(privateKey).getPubKey()); + } + + public static byte[] getPublicKeyFromPrivate(String privateKey) { + BigInteger tmpKey = new BigInteger(privateKey, 16); + return ECKey.publicKeyFromPrivate(tmpKey, true); + } + + public static String getSM2RandomPrivateKey() { + SM2 key = new SM2(Utils.getRandom()); + return Hex.toHexString( + Objects.requireNonNull(key.getPrivKeyBytes())); + } + + public static SM2 getSM2byPrivate(String privateKey) { + BigInteger priK = new BigInteger(privateKey, 16); + return SM2.fromPrivate(priK); + } + + public static String getSM2PublicByPrivateKey(String privateKey) { + return Hex.toHexString(getSM2byPrivate(privateKey).getPubKey()); + } + + public static String getSM2AddressByPrivateKey(String privateKey) { + return ByteArray + .toHexString(getSM2byPrivate(privateKey).getAddress()); + } + + public static byte[] getSM2PublicKeyFromPrivate(String privateKey) { + BigInteger tmpKey = new BigInteger(privateKey, 16); + return SM2.publicKeyFromPrivate(tmpKey, true); + } + + public static byte[] getSM2HashByPubKey(byte[] pubKey, String message) { + SM2 key = SM2.fromPublicOnly(pubKey); + SM2Signer signer = key.getSM2SignerForHash(); + return signer.generateSM3Hash(message.getBytes()); + } + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI jsonStr2Abi(String jsonStr) { + if (jsonStr == null) { + return null; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContractOuterClass.SmartContract.ABI.Builder abiBuilder = + SmartContractOuterClass.SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null + && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null + && abiItem.getAsJsonObject().get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null + ? abiItem.getAsJsonObject().get("name").getAsString() + : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null + ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null + ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() : null; + String type = + abiItem.getAsJsonObject().get("type") != null + ? abiItem.getAsJsonObject().get("type").getAsString() : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null + && abiItem.getAsJsonObject().get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null + ? abiItem.getAsJsonObject().get("stateMutability").getAsString() + : null; + if (type == null) { + logger.error("No type!"); + return null; + } + if (!type.equalsIgnoreCase("fallback") && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContractOuterClass.SmartContract.ABI.Entry.Builder entryBuilder = + SmartContractOuterClass.SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); + return null; + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + SmartContractOuterClass.SmartContract.ABI.Entry.Param.Builder paramBuilder + = SmartContractOuterClass.SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); + return null; + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContractOuterClass.SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContractOuterClass.SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); + } + } + + entryBuilder.setType(getEntryType(type)); + entryBuilder.setPayable(payable); + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } + + abiBuilder.addEntrys(entryBuilder.build()); + } + + return abiBuilder.build(); + } + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI.Entry.EntryType + getEntryType(String type) { + switch (type) { + case "constructor": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Fallback; + case "error": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Error; + default: + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } + } + + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType + getStateMutability(String stateMutability) { + switch (stateMutability) { + case "pure": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Pure; + case "view": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.View; + case "nonpayable": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; + case "payable": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Payable; + default: + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; + } + } + /** * Convert to pub. * @param priKey private key @@ -102,4 +325,31 @@ public static GrpcAPI.Return broadcastTransaction( } return response; } + + public static int chooseRandomPort() { + return chooseRandomPort(10240, 65000); + } + + public static int chooseRandomPort(int min, int max) { + int port = new Random().nextInt(max - min + 1) + min; + try { + while (!checkPortAvailable(port)) { + port = new Random().nextInt(max - min + 1) + min; + } + } catch (IOException e) { + return new Random().nextInt(max - min + 1) + min; + } + return port; + } + + private static boolean checkPortAvailable(int port) throws IOException { + InetAddress theAddress = InetAddress.getByName("127.0.0.1"); + try (Socket socket = new Socket(theAddress, port)) { + // only check + socket.getPort(); + } catch (IOException e) { + return true; + } + return false; + } } diff --git a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java index a0164190b8c..51745e96e92 100644 --- a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java +++ b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java @@ -3,8 +3,8 @@ import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.junit.Assert; +import org.junit.Test; import org.tron.common.parameter.CommonParameter; public class Sha256HashTest { @@ -17,10 +17,10 @@ public void testHash() { .getInstance().isECKeyCryptoEngine(), input); byte[] hash1 = Sha256Hash.hash(CommonParameter .getInstance().isECKeyCryptoEngine(), hash0); - Assert.assertEquals(hash0, ByteArray - .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084")); - Assert.assertEquals(hash1, ByteArray - .fromHexString("10AE21E887E8FE30C591A22A5F8BB20EB32B2A739486DC5F3810E00BBDB58C5C")); + Assert.assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray + .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084"))); + Assert.assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray + .fromHexString("10AE21E887E8FE30C591A22A5F8BB20EB32B2A739486DC5F3810E00BBDB58C5C"))); } @@ -40,7 +40,7 @@ public void testMultiThreadingHash() { countAll.incrementAndGet(); if (!Arrays.equals(hash, hash0)) { countFailed.incrementAndGet(); - Assert.assertTrue(false); + Assert.fail(); } } }); diff --git a/framework/src/test/java/stest/tron/wallet/common/client/Configuration.java b/framework/src/test/java/org/tron/common/utils/client/Configuration.java similarity index 90% rename from framework/src/test/java/stest/tron/wallet/common/client/Configuration.java rename to framework/src/test/java/org/tron/common/utils/client/Configuration.java index 9d0cdd050c8..79dded303aa 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/Configuration.java +++ b/framework/src/test/java/org/tron/common/utils/client/Configuration.java @@ -1,6 +1,4 @@ -package stest.tron.wallet.common.client; - -import static org.apache.commons.lang3.StringUtils.isBlank; +package org.tron.common.utils.client; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; @@ -8,6 +6,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,7 +21,7 @@ public class Configuration { */ public static Config getByPath(final String configurationPath) { - if (isBlank(configurationPath)) { + if (StringUtils.isBlank(configurationPath)) { throw new IllegalArgumentException("Configuration path is required!"); } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java rename to framework/src/test/java/org/tron/common/utils/client/GrpcClient.java index 11482d4af83..139485e4e2b 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java @@ -1,10 +1,11 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.Optional; import java.util.concurrent.TimeUnit; + import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.AccountNetMessage; import org.tron.api.GrpcAPI.AccountPaginated; @@ -35,7 +36,6 @@ import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; import org.tron.protos.contract.WitnessContract; - public class GrpcClient { private ManagedChannel channelFull = null; @@ -46,7 +46,7 @@ public class GrpcClient { // public GrpcClient(String host, int port) { // channel = ManagedChannelBuilder.forAddress(host, port) - // .usePlaintext(true) + // .usePlaintext() // .build(); // blockingStub = WalletGrpc.newBlockingStub(channel); // } @@ -58,13 +58,13 @@ public class GrpcClient { public GrpcClient(String fullnode, String soliditynode) { if (!(fullnode.isEmpty())) { channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } if (!(soliditynode.isEmpty())) { channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); diff --git a/framework/src/test/java/stest/tron/wallet/common/client/Parameter.java b/framework/src/test/java/org/tron/common/utils/client/Parameter.java similarity index 89% rename from framework/src/test/java/stest/tron/wallet/common/client/Parameter.java rename to framework/src/test/java/org/tron/common/utils/client/Parameter.java index 8fead433c2e..f0531c95165 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/Parameter.java +++ b/framework/src/test/java/org/tron/common/utils/client/Parameter.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; public interface Parameter { @@ -11,4 +11,4 @@ interface CommonConstant { byte ADD_PRE_FIX_BYTE_MAINNET = (byte) 0x41; //41 + address byte ADD_PRE_FIX_BYTE_TESTNET = (byte) 0xa0; //a0 + address } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java rename to framework/src/test/java/org/tron/common/utils/client/WalletClient.java index c4bd7ae29d3..37b67ffaa46 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java @@ -1,9 +1,10 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; + import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; @@ -12,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; + import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.encoders.Hex; import org.slf4j.Logger; @@ -28,6 +30,9 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.Parameter.CommonConstant; +import org.tron.common.utils.client.utils.Base58; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.core.exception.CancelException; import org.tron.core.exception.CipherException; import org.tron.protos.Protocol.Account; @@ -45,9 +50,6 @@ import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.TransactionUtils; public class WalletClient { @@ -246,7 +248,7 @@ public static Transaction createTransferAssetTransaction(byte[] to, byte[] asser public static Transaction participateAssetIssueTransaction(byte[] to, byte[] assertName, byte[] owner, long amount) { - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = + ParticipateAssetIssueContract contract = participateAssetIssueContract(to, assertName, owner, amount); return rpcCli.createParticipateAssetIssueTransaction(contract); } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java b/framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java similarity index 85% rename from framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java rename to framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java index c032fce9eff..43e10441c51 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java +++ b/framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import java.util.Comparator; import org.tron.protos.Protocol.Witness; @@ -8,4 +8,4 @@ class WitnessComparator implements Comparator { public int compare(Object o1, Object o2) { return Long.compare(((Witness) o2).getVoteCount(), ((Witness) o1).getVoteCount()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java rename to framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java index 9eb2bf3a8c0..976490b8c80 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java rename to framework/src/test/java/org/tron/common/utils/client/utils/Base58.java index 6fd13777927..2106b191af9 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java @@ -1,7 +1,8 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import java.io.UnsupportedEncodingException; import java.math.BigInteger; + import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Commons; import org.tron.common.utils.Sha256Hash; @@ -240,4 +241,4 @@ public static byte[] decode58CheckForShield(String input) { } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java b/framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java index 7a41ed44b23..1775f28ac17 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright (c) [2016] [ ] * This file is part of the ethereumJ library. @@ -19,6 +19,7 @@ import java.io.Serializable; import java.util.Arrays; + import org.bouncycastle.util.encoders.Hex; import org.tron.common.utils.FastByteComparisons; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java rename to framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java index e44ac34e765..6c36f4d636a 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright (c) [2016] [ ] @@ -22,6 +22,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigInteger; import java.nio.ByteBuffer; + import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.tron.common.utils.ByteUtil; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java rename to framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java index adb7c0e54a0..0d117dd4a45 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; @@ -6,16 +6,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.google.protobuf.ByteString; -import io.netty.util.internal.StringUtil; - import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; - import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -31,8 +26,8 @@ import org.tron.api.GrpcAPI; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.Configuration; @Slf4j public class HttpMethed { @@ -106,7 +101,7 @@ public static HttpResponse setAccountId( JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("account_id", accountId); userBaseObj2.addProperty( - "owner_address", Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); + "owner_address", Base58.encode58Check(PublicMethod.getFinalAddress(fromKey))); userBaseObj2.addProperty("visible", visable); response = createConnect(requestUrl, userBaseObj2); transactionString = EntityUtils.toString(response.getEntity()); @@ -2225,18 +2220,33 @@ public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { public static void waitToProduceOneBlock(String httpNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + if (responseContent.containsKey("block_header")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("block_header").toString()); + } + if (responseContent.containsKey("raw_data")) { + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + } + Integer currentBlockNum = 0; + if (responseContent.containsKey("number")) { + currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + } Integer nextBlockNum = 0; Integer times = 0; while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); - responseContent = - HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + if (responseContent.containsKey("block_header")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("block_header").toString()); + } + if (responseContent.containsKey("raw_data")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("raw_data").toString()); + } + if (responseContent.containsKey("number")) { + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + } try { Thread.sleep(1200); } catch (InterruptedException e) { @@ -3109,97 +3119,7 @@ public static HttpResponse clearABiGetTxid( return response; } - /** constructor. */ - public static Optional generateShieldAddress(String httpnode) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - String sk; - String d; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD; - try { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - sk = responseContent.getString("value"); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - d = responseContent.getString("d"); - - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - ak = responseContent.getString("value"); - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - nk = responseContent.getString("value"); - - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - ivk = responseContent.getString("ivk"); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); - responseContent = HttpMethed.parseResponseContent(response); - pkD = responseContent.getString("pkD"); - - addressInfo.setSk(ByteArray.fromHexString(sk)); - addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); - addressInfo.setIvk(ByteArray.fromHexString(ivk)); - addressInfo.setOvk(ByteArray.fromHexString(ovk)); - addressInfo.setPkD(ByteArray.fromHexString(pkD)); - logger.info("sk:" + sk); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** constructor. */ - public static List addShieldOutputList( - String httpNode, - List shieldOutList, - String shieldToAddress, - String toAmountString, - String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - - response = HttpMethed.getRcm(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - String rcm = responseContent.getString("value"); - - noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } /** constructor. */ public static HttpResponse getSpendingKey(String httpNode) { @@ -3301,19 +3221,6 @@ public static HttpResponse getIncomingViewingKey(String httpNode, String ak, Str return response; } - /** constructor. */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** constructor. */ public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { try { diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java b/framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java old mode 100755 new mode 100644 similarity index 77% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java rename to framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java index b482068f118..bab667dedf1 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java @@ -1,11 +1,11 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONObject; - -public class JSONObjectWarp extends JSONObject { - - public JSONObjectWarp put(String key, Object value) { - super.put(key, value); - return this; - } -} +package org.tron.common.utils.client.utils; + +import com.alibaba.fastjson.JSONObject; + +public class JSONObjectWarp extends JSONObject { + + public JSONObjectWarp put(String key, Object value) { + super.put(key, value); + return this; + } +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java rename to framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java index 478bd280440..fde88385794 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright 2011 Google Inc. @@ -16,9 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import static com.google.common.base.Preconditions.checkArgument; - +import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; @@ -31,6 +29,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; + import org.bouncycastle.crypto.digests.SM3Digest; import org.tron.common.utils.ByteArray; @@ -59,13 +58,13 @@ public class Sha256Sm3Hash implements Serializable, Comparable { public Sha256Sm3Hash(long num, byte[] hash) { byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } @@ -74,7 +73,7 @@ public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { */ @Deprecated public Sha256Sm3Hash(byte[] rawHashBytes) { - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java index 35332287e93..5d0de50c0b8 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import java.util.Arrays; import java.util.Optional; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java index 8691ac26abc..50fad817c56 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import lombok.AllArgsConstructor; import lombok.Getter; @@ -78,4 +78,3 @@ public boolean decode(final String data) { } } - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java rename to framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java index 179af83e083..b6226d01aae 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * java-tron is free software: you can redistribute it and/or modify diff --git a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java index 4d000d375b5..69501c4e393 100755 --- a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java +++ b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java @@ -2,26 +2,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.BandwidthProcessor; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractValidateException; @@ -34,9 +28,8 @@ import org.tron.protos.contract.BalanceContract.TransferContract; @Slf4j -public class BandwidthProcessorTest { +public class BandwidthProcessorTest extends BaseTest { - private static final String dbPath = "output_bandwidth_test"; private static final String ASSET_NAME; private static final String ASSET_NAME_V2; private static final String OWNER_ADDRESS; @@ -49,16 +42,13 @@ public class BandwidthProcessorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static long START_TIME; - private static long END_TIME; + private static final long START_TIME; + private static final long END_TIME; static { + dbPath = "output_bandwidth_processor_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); ASSET_NAME = "test_token"; ASSET_NAME_V2 = "2"; OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -69,29 +59,6 @@ public class BandwidthProcessorTest { END_TIME = DateTime.now().getMillis(); } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/BlockCapsuleTest.java deleted file mode 100644 index ad129c6d471..00000000000 --- a/framework/src/test/java/org/tron/core/BlockCapsuleTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * java-tron is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * java-tron is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package org.tron.core; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class BlockCapsuleTest { - -} diff --git a/framework/src/test/java/org/tron/core/BlockUtilTest.java b/framework/src/test/java/org/tron/core/BlockUtilTest.java index 25e998d7a70..b122c3082f7 100644 --- a/framework/src/test/java/org/tron/core/BlockUtilTest.java +++ b/framework/src/test/java/org/tron/core/BlockUtilTest.java @@ -69,9 +69,7 @@ public void testBlockUtil() { .fromHexString(blockCapsule2.getBlockId().toString()))) )).build()); - Assert.assertEquals(false, BlockUtil.isParentOf(blockCapsule1, blockCapsule2)); Assert.assertFalse(BlockUtil.isParentOf(blockCapsule1, blockCapsule2)); - Assert.assertEquals(true, BlockUtil.isParentOf(blockCapsule2, blockCapsule3)); Assert.assertTrue(BlockUtil.isParentOf(blockCapsule2, blockCapsule3)); } } diff --git a/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java b/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java index e787fe16e96..4bcef1e148c 100644 --- a/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java +++ b/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java @@ -1,6 +1,6 @@ package org.tron.core; -import static stest.tron.wallet.common.client.WalletClient.decodeFromBase58Check; +import static org.tron.common.utils.client.WalletClient.decodeFromBase58Check; import com.google.protobuf.Any; import com.google.protobuf.ByteString; @@ -16,14 +16,14 @@ public class CreateCommonTransactionTest { - private static String fullnode = "127.0.0.1:50051"; + private static final String FULL_NODE = "127.0.0.1:50051"; /** * for example create UpdateBrokerageContract */ public static void testCreateUpdateBrokerageContract() { WalletBlockingStub walletStub = WalletGrpc - .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build()); + .newBlockingStub(ManagedChannelBuilder.forTarget(FULL_NODE).usePlaintext().build()); UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); updateBrokerageContract.setOwnerAddress( ByteString.copyFrom(decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz"))) diff --git a/framework/src/test/java/org/tron/core/EnergyProcessorTest.java b/framework/src/test/java/org/tron/core/EnergyProcessorTest.java index b66b79ba07f..da0493e2026 100755 --- a/framework/src/test/java/org/tron/core/EnergyProcessorTest.java +++ b/framework/src/test/java/org/tron/core/EnergyProcessorTest.java @@ -1,69 +1,37 @@ package org.tron.core; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.AdaptiveResourceLimitConstants; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; import org.tron.core.db.EnergyProcessor; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.Common; @Slf4j -public class EnergyProcessorTest { +public class EnergyProcessorTest extends BaseTest { - private static final String dbPath = "EnergyProcessorTest"; private static final String ASSET_NAME; private static final String CONTRACT_PROVIDER_ADDRESS; private static final String USER_ADDRESS; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; static { + dbPath = "energy_processor_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); ASSET_NAME = "test_token"; CONTRACT_PROVIDER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; USER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -130,7 +98,63 @@ public void testUseContractCreatorEnergy() throws Exception { Assert.assertEquals(1526647838000L, ownerCapsuleNew.getAccountResource().getLatestConsumeTimeForEnergy()); Assert.assertEquals(10000L, ownerCapsuleNew.getAccountResource().getEnergyUsage()); + } + @Test + public void testUseEnergyInWindowSizeV2() throws Exception { + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(10000L); + dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(2849288700L); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(CONTRACT_PROVIDER_ADDRESS)); + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + EnergyProcessor processor = + new EnergyProcessor(dbManager.getDynamicPropertiesStore(), dbManager.getAccountStore()); + long energy = 2345L; + long now = 9999L; + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + } + processor.useEnergy(ownerCapsule, energy, now); + Assert.assertEquals(72368521, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(300, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertFalse(ownerCapsule.getWindowOptimized(Common.ResourceCode.ENERGY)); + + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + } + processor.useEnergy(ownerCapsule, energy, now); + + Assert.assertEquals(72368521L, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(1224, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertEquals(1224919, ownerCapsule.getWindowSizeV2(Common.ResourceCode.ENERGY)); + Assert.assertTrue(ownerCapsule.getWindowOptimized(Common.ResourceCode.ENERGY)); + + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + now++; + } + Assert.assertEquals(15844971L, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(2086, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertEquals(2086556, ownerCapsule.getWindowSizeV2(Common.ResourceCode.ENERGY)); } @Test diff --git a/framework/src/test/java/org/tron/core/ForkControllerTest.java b/framework/src/test/java/org/tron/core/ForkControllerTest.java new file mode 100644 index 00000000000..20a28f9b619 --- /dev/null +++ b/framework/src/test/java/org/tron/core/ForkControllerTest.java @@ -0,0 +1,261 @@ +package org.tron.core; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter; +import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; + +public class ForkControllerTest { + private static ChainBaseManager chainBaseManager; + private static DynamicPropertiesStore dynamicPropertiesStore; + private static final ForkController forkController = ForkController.instance(); + private static TronApplicationContext context; + private static final String dbPath = "output_fork_test"; + private static long ENERGY_LIMIT_BLOCK_NUM = 4727890L; + + @Before + public void init() { + Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + dynamicPropertiesStore = context.getBean(DynamicPropertiesStore.class); + chainBaseManager = context.getBean(ChainBaseManager.class); + forkController.init(chainBaseManager); + } + + @Test + public void testPass() { + boolean flag = forkController.pass(Parameter.ForkBlockVersionEnum.ENERGY_LIMIT); + Assert.assertFalse(flag); + + dynamicPropertiesStore.saveLatestBlockHeaderNumber(ENERGY_LIMIT_BLOCK_NUM); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.ENERGY_LIMIT); + Assert.assertTrue(flag); + + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + byte[] stats = new byte[3]; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + stats[0] = 1; + stats[1] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + stats[2] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertTrue(flag); + + stats = new byte[5]; + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + stats[0] = 1; + stats[1] = 1; + stats[2] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + stats[3] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertTrue(flag); + } + + @Test + public void testReset() { + List list = new ArrayList<>(); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + + byte[] stats1 = {1, 1, 1, 1, 1}; + byte[] stats2 = {1, 1, 1, 1, 0}; + byte[] stats3 = {1, 1, 1, 0, 0}; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats1); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue(), stats3); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + forkController.reset(); + + byte[] bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue()); + Assert.assertEquals(getSum(bytes), 5); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(getSum(bytes), 0); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 4); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 0); + list.add(ByteString.copyFrom(new byte[32])); + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + forkController.reset(); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(bytes.length, 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(bytes.length, 6); + } + + @Test + public void testUpdate() { + List list = new ArrayList<>(); + list.add(ByteString.copyFrom(getBytes(1))); + list.add(ByteString.copyFrom(getBytes(2))); + list.add(ByteString.copyFrom(getBytes(3))); + list.add(ByteString.copyFrom(getBytes(4))); + list.add(ByteString.copyFrom(getBytes(5))); + + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + + byte[] stats1 = {1, 1, 1, 1, 1}; + byte[] stats2 = {1, 1, 1, 1, 0}; + byte[] stats3 = {1, 1, 1, 0, 0}; + + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats1); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue(), stats3); + + BlockCapsule blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_3_5); + + forkController.update(blockCapsule); + + byte[] bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(0, bytes[0]); + + blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_4_5); + forkController.update(blockCapsule); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(1, bytes[0]); + + blockCapsule = getBlock(4, Parameter.ForkBlockVersionEnum.VERSION_4_5); + forkController.update(blockCapsule); + blockCapsule = getBlock(5, Parameter.ForkBlockVersionEnum.VERSION_4_5); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + forkController.update(blockCapsule); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_3.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 4); + + blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_4_3); + forkController.update(blockCapsule); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 4); + } + + private BlockCapsule getBlock(int i, Parameter.ForkBlockVersionEnum versionEnum) { + org.tron.protos.Protocol.BlockHeader.raw rawData = + org.tron.protos.Protocol.BlockHeader.raw.newBuilder() + .setVersion(versionEnum.getValue()) + .setWitnessAddress(ByteString.copyFrom(getBytes(i))) + .build(); + + Protocol.BlockHeader blockHeader = Protocol.BlockHeader.newBuilder() + .setRawData(rawData).build(); + + Protocol.Block block = Protocol.Block.newBuilder().setBlockHeader(blockHeader).build(); + + return new BlockCapsule(block); + } + + private int getSum(byte[] bytes) { + int sum = 0; + for (byte aByte : bytes) { + sum += aByte; + } + return sum; + } + + private byte[] getBytes(int i) { + byte[] bytes = new byte[21]; + bytes[i] = 1; + return bytes; + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + +} diff --git a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java index ba407b42e0b..e7fefd5e121 100644 --- a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java +++ b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java @@ -3,21 +3,18 @@ import static org.tron.core.zksnark.LibrustzcashTest.librustzcashInitZksnarkParams; import com.google.protobuf.ByteString; -import java.io.File; import java.math.BigInteger; import java.util.Arrays; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.BytesMessage; import org.tron.api.GrpcAPI.PrivateShieldedTRC20Parameters; @@ -25,20 +22,18 @@ import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; import org.tron.api.GrpcAPI.ShieldedTRC20TriggerContractParameters; import org.tron.api.GrpcAPI.SpendAuthSigParameters; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.WalletClient; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; import org.tron.common.zksnark.LibrustzcashParam; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.BlockGenerate; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ZksnarkException; @@ -56,17 +51,12 @@ import org.tron.core.zen.note.Note; import org.tron.protos.contract.ShieldContract; import org.tron.protos.contract.ShieldContract.SpendDescription; -import stest.tron.wallet.common.client.WalletClient; @Slf4j -public class ShieldedTRC20BuilderTest extends BlockGenerate { - - private static String dbPath = "output_Shielded_TRC20_Api_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; - private String privateKey = "650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812"; - private String pubAddress = "TFsrP7YcSSRwHzLPwaCnXyTKagHs8rXKNJ"; +public class ShieldedTRC20BuilderTest extends BaseTest { + @Resource + private Wallet wallet; + private String priKey = PublicMethod.getRandomPrivateKey(); private static final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; private static final byte[] SHIELDED_CONTRACT_ADDRESS; private static final byte[] DEFAULT_OVK; @@ -74,8 +64,8 @@ public class ShieldedTRC20BuilderTest extends BlockGenerate { private static final byte[] PUBLIC_TO_ADDRESS; static { + dbPath = "output_Shielded_TRC20_Api_test"; Args.setParam(new String[]{"--output-directory", dbPath}, "config-test-mainnet.conf"); - context = new TronApplicationContext(DefaultConfig.class); SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); DEFAULT_OVK = ByteArray .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); @@ -87,25 +77,6 @@ public class ShieldedTRC20BuilderTest extends BlockGenerate { VerifyTransferProof transferContract = new VerifyTransferProof(); VerifyBurnProof burnContract = new VerifyBurnProof(); - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - dbManager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(1); - dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Before public void before() { } @@ -121,7 +92,7 @@ public void createShieldedContractParametersForMint() for (int countNum = 0; countNum < totalCountNum; countNum++) { GrpcAPI.PrivateShieldedTRC20Parameters mintPrivateParam1 = mintParams( - privateKey, value, SHIELDED_CONTRACT_ADDRESS_STR, null); + priKey, value, SHIELDED_CONTRACT_ADDRESS_STR, null); GrpcAPI.ShieldedTRC20Parameters trc20MintParams = wallet .createShieldedContractParameters(mintPrivateParam1); @@ -132,7 +103,7 @@ public void createShieldedContractParametersForMint() Assert.assertEquals(1, result[31]); //update frontier and leafCount - + int slot = result[63]; if (slot == 0) { System.arraycopy(inputData, 0, frontier, 0, 32); @@ -159,7 +130,7 @@ public void createShieldedContractParametersForTransfer1to1() IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( new IncrementalMerkleTreeCapsule()); for (int countNum = 0; countNum < totalCountNum; countNum++) { - SpendingKey senderSk = SpendingKey.decode(privateKey); + SpendingKey senderSk = SpendingKey.decode(priKey); FullViewingKey senderFvk = senderSk.fullViewingKey(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; @@ -2203,7 +2174,6 @@ public void createShieldedContractParametersWithoutAskForBurn1to2() @Test public void getTriggerInputForForMint() throws Exception { librustzcashInitZksnarkParams(); - byte[] callerAddress = WalletClient.decodeFromBase58Check(pubAddress); SpendingKey sk = SpendingKey.random(); ExpandedSpendingKey expsk = sk.expandedSpendingKey(); byte[] ovk = expsk.getOvk(); @@ -2273,7 +2243,7 @@ public void testScanShieldedTRC20NotesByIvk() throws Exception { int statNum = 1; int endNum = 100; librustzcashInitZksnarkParams(); - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); byte[] ivk = fvk.inViewingKey().value; @@ -2289,7 +2259,7 @@ public void testScanShieldedTRC20NotesByIvk() throws Exception { public void testscanShieldedTRC20NotesByOvk() throws Exception { int statNum = 9200; int endNum = 9240; - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); GrpcAPI.DecryptNotesTRC20 scannedNotes = wallet.scanShieldedTRC20NotesByOvk( @@ -2305,7 +2275,7 @@ public void isShieldedTRC20ContractNoteSpent() throws Exception { int statNum = 9200; int endNum = 9240; librustzcashInitZksnarkParams(); - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); byte[] ivk = fvk.inViewingKey().value; diff --git a/framework/src/test/java/org/tron/core/StorageMarketTest.java b/framework/src/test/java/org/tron/core/StorageMarketTest.java index 039f919c9f4..1c471032861 100644 --- a/framework/src/test/java/org/tron/core/StorageMarketTest.java +++ b/framework/src/test/java/org/tron/core/StorageMarketTest.java @@ -4,70 +4,29 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.StorageMarket; import org.tron.protos.Protocol.AccountType; import org.tron.protos.contract.StorageContract.BuyStorageContract; @Slf4j -public class StorageMarketTest { +public class StorageMarketTest extends BaseTest { - private static final String dbPath = "output_storage_market_test"; private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000_000_000L; - private static Manager dbManager; private static StorageMarket storageMarket; - private static TronApplicationContext context; static { + dbPath = "output_storage_market_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - storageMarket = new StorageMarket(dbManager.getAccountStore(), - dbManager.getDynamicPropertiesStore()); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -75,6 +34,9 @@ public static void destroy() { */ @Before public void createAccountCapsule() { + storageMarket = new StorageMarket(dbManager.getAccountStore(), + dbManager.getDynamicPropertiesStore()); + AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFromUtf8("owner"), diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 4c0545f3c78..15b51f51edf 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -20,24 +20,22 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; +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.BANDWIDTH; import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; - +import javax.annotation.Resource; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.tron.api.GrpcAPI; @@ -45,10 +43,9 @@ import org.tron.api.GrpcAPI.BlockList; import org.tron.api.GrpcAPI.ExchangeList; import org.tron.api.GrpcAPI.ProposalList; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Utils; import org.tron.core.actuator.DelegateResourceActuator; import org.tron.core.actuator.FreezeBalanceActuator; @@ -65,9 +62,7 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.NonUniqueObjectException; @@ -76,7 +71,6 @@ import org.tron.core.utils.TransactionUtil; import org.tron.core.vm.program.Program; import org.tron.protos.Protocol; -import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.BlockHeader; import org.tron.protos.Protocol.BlockHeader.raw; @@ -94,21 +88,18 @@ @Slf4j -public class WalletTest { +public class WalletTest extends BaseTest { public static final String ACCOUNT_ADDRESS_ONE = "121212a9cf"; public static final String ACCOUNT_ADDRESS_TWO = "232323a9cf"; public static final String ACCOUNT_ADDRESS_THREE = "343434a9cf"; public static final String ACCOUNT_ADDRESS_FOUR = "454545a9cf"; public static final String ACCOUNT_ADDRESS_FIVE = "565656a9cf"; - public static final String ACCOUNT_ADDRESS_SIX = "12344349cf"; public static final long BLOCK_NUM_ONE = 1; public static final long BLOCK_NUM_TWO = 2; public static final long BLOCK_NUM_THREE = 3; public static final long BLOCK_NUM_FOUR = 4; public static final long BLOCK_NUM_FIVE = 5; - public static final long CYCLE_NUM_ONE = 1; - public static final long CYCLE_NUM_TWO = 2; public static final long BLOCK_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); public static final long BLOCK_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); public static final long BLOCK_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); @@ -119,16 +110,13 @@ public class WalletTest { public static final long BLOCK_WITNESS_THREE = 14; public static final long BLOCK_WITNESS_FOUR = 15; public static final long BLOCK_WITNESS_FIVE = 16; - //private static DeferredTransaction deferredTransaction; public static final long TRANSACTION_TIMESTAMP_ONE = DateTime.now().minusDays(4).getMillis(); public static final long TRANSACTION_TIMESTAMP_TWO = DateTime.now().minusDays(3).getMillis(); public static final long TRANSACTION_TIMESTAMP_THREE = DateTime.now().minusDays(2).getMillis(); public static final long TRANSACTION_TIMESTAMP_FOUR = DateTime.now().minusDays(1).getMillis(); public static final long TRANSACTION_TIMESTAMP_FIVE = DateTime.now().getMillis(); - private static TronApplicationContext context; - private static Wallet wallet; - private static ChainBaseManager chainBaseManager; - private static String dbPath = "output_wallet_test"; + @Resource + private Wallet wallet; private static Block block1; private static Block block2; private static Block block3; @@ -139,70 +127,37 @@ public class WalletTest { private static Transaction transaction3; private static Transaction transaction4; private static Transaction transaction5; - private static Transaction transaction6; private static AssetIssueCapsule Asset1; - private static Manager dbManager; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final long initBalance = 43_200_000_000L; + private static boolean init; static { + dbPath = "output_wallet_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; } - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - dbManager = context.getBean(Manager.class); + @Before + public void before() { + initAccountCapsule(); + if (init) { + return; + } initTransaction(); initBlock(); chainBaseManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); chainBaseManager.getDelegatedResourceStore().reset(); - } - - @Before - public void createAccountCapsule() { - AccountCapsule ownerCapsule = - new AccountCapsule( - ByteString.copyFromUtf8("owner"), - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - AccountType.Normal, - initBalance); - dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); - - AccountCapsule receiverCapsule = - new AccountCapsule( - ByteString.copyFromUtf8("receiver"), - ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), - AccountType.Normal, - initBalance); - dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); - - byte[] dbKey = DelegatedResourceCapsule.createDbKey( - ByteArray.fromHexString(OWNER_ADDRESS), - ByteArray.fromHexString(RECEIVER_ADDRESS)); - byte[] dbKeyV2 = DelegatedResourceCapsule.createDbKeyV2( - ByteArray.fromHexString(OWNER_ADDRESS), - ByteArray.fromHexString(RECEIVER_ADDRESS), - false); - chainBaseManager.getDelegatedResourceStore().delete(dbKey); - chainBaseManager.getDelegatedResourceStore().delete(dbKeyV2); - chainBaseManager.getDelegatedResourceAccountIndexStore() - .delete(ByteArray.fromHexString(OWNER_ADDRESS)); - - dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0L); + init = true; } /** * initTransaction. */ - private static void initTransaction() { + private void initTransaction() { transaction1 = getBuildTransaction( getBuildTransferContract(ACCOUNT_ADDRESS_ONE, ACCOUNT_ADDRESS_TWO), TRANSACTION_TIMESTAMP_ONE, BLOCK_NUM_ONE); @@ -227,20 +182,48 @@ private static void initTransaction() { getBuildTransferContract(ACCOUNT_ADDRESS_FIVE, ACCOUNT_ADDRESS_ONE), TRANSACTION_TIMESTAMP_FIVE, BLOCK_NUM_FIVE); addTransactionToStore(transaction5); + } - transaction6 = getBuildTransaction( - getBuildTransferContract(ACCOUNT_ADDRESS_ONE, ACCOUNT_ADDRESS_SIX), - TRANSACTION_TIMESTAMP_FIVE, BLOCK_NUM_FIVE); - addTransactionToStore(transaction5); + private void initAccountCapsule() { + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + + byte[] dbKey = DelegatedResourceCapsule.createDbKey( + ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS)); + byte[] dbKeyV2 = DelegatedResourceCapsule.createDbKeyV2( + ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), + false); + chainBaseManager.getDelegatedResourceStore().delete(dbKey); + chainBaseManager.getDelegatedResourceStore().delete(dbKeyV2); + chainBaseManager.getDelegatedResourceAccountIndexStore() + .delete(ByteArray.fromHexString(OWNER_ADDRESS)); + + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0L); } - private static void addTransactionToStore(Transaction transaction) { + private void addTransactionToStore(Transaction transaction) { TransactionCapsule transactionCapsule = new TransactionCapsule(transaction); chainBaseManager.getTransactionStore() .put(transactionCapsule.getTransactionId().getBytes(), transactionCapsule); } - private static void addTransactionInfoToStore(Transaction transaction) { + private void addTransactionInfoToStore(Transaction transaction) { TransactionInfoCapsule transactionInfo = new TransactionInfoCapsule(); byte[] trxId = transaction.getRawData().toByteArray(); transactionInfo.setId(trxId); @@ -268,7 +251,7 @@ private static TransferContract getBuildTransferContract(String ownerAddress, St /** * initBlock. */ - private static void initBlock() { + private void initBlock() { block1 = getBuildBlock(BLOCK_TIMESTAMP_ONE, BLOCK_NUM_ONE, BLOCK_WITNESS_ONE, ACCOUNT_ADDRESS_ONE, transaction1, transaction2); @@ -296,7 +279,7 @@ private static void initBlock() { addTransactionInfoToStore(transaction5); } - private static void addBlockToStore(Block block) { + private void addBlockToStore(Block block) { BlockCapsule blockCapsule = new BlockCapsule(block); chainBaseManager.getBlockStore().put(blockCapsule.getBlockId().getBytes(), blockCapsule); } @@ -311,14 +294,14 @@ private static Block getBuildBlock(long timestamp, long num, long witnessId, } - private static void buildAssetIssue() { + private void buildAssetIssue() { AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); builder.setName(ByteString.copyFromUtf8("Asset1")); Asset1 = new AssetIssueCapsule(builder.build()); chainBaseManager.getAssetIssueStore().put(Asset1.createDbKey(), Asset1); } - private static void buildProposal() { + private void buildProposal() { Proposal.Builder builder = Proposal.newBuilder(); builder.setProposalId(1L).setProposerAddress(ByteString.copyFromUtf8("Address1")); ProposalCapsule proposalCapsule = new ProposalCapsule(builder.build()); @@ -330,7 +313,7 @@ private static void buildProposal() { chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(2L); } - private static void buildExchange() { + private void buildExchange() { Exchange.Builder builder = Exchange.newBuilder(); builder.setExchangeId(1L).setCreatorAddress(ByteString.copyFromUtf8("Address1")); ExchangeCapsule ExchangeCapsule = new ExchangeCapsule(builder.build()); @@ -344,13 +327,6 @@ private static void buildExchange() { } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - @Test public void testWallet() { Wallet wallet1 = new Wallet(); @@ -359,7 +335,7 @@ public void testWallet() { .getAddress())); logger.info("wallet2 address = {}", ByteArray.toHexString(wallet2 .getAddress())); - assertFalse(wallet1.getAddress().equals(wallet2.getAddress())); + assertNotEquals(wallet1.getAddress(), wallet2.getAddress()); } @Test @@ -376,7 +352,6 @@ public void testGetAddress() { @Test public void testGetEcKey() { ECKey ecKey = new ECKey(Utils.getRandom()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); Wallet wallet1 = new Wallet(ecKey); logger.info("ecKey address = {}", ByteArray.toHexString(ecKey .getAddress())); @@ -389,6 +364,7 @@ public void testGetEcKey() { public void ss() { for (int i = 0; i < 4; i++) { ECKey ecKey = new ECKey(Utils.getRandom()); + assertNotNull(ecKey); System.out.println(i + 1); System.out.println("privateKey:" + ByteArray.toHexString(ecKey.getPrivKeyBytes())); System.out.println("publicKey:" + ByteArray.toHexString(ecKey.getPubKey())); @@ -507,17 +483,16 @@ public void getBlockByLatestNum() { public void getPaginatedAssetIssueList() { buildAssetIssue(); AssetIssueList assetList1 = wallet.getAssetIssueList(0, 100); - Assert.assertTrue("get Asset1", - assetList1.getAssetIssue(0).getName().equals(Asset1.getName())); + assertEquals("get Asset1", assetList1.getAssetIssue(0).getName(), Asset1.getName()); try { - assetList1.getAssetIssue(1); + assertNotNull(assetList1.getAssetIssue(1)); } catch (Exception e) { Assert.assertTrue("AssetIssueList1 size should be 1", true); } AssetIssueList assetList2 = wallet.getAssetIssueList(0, 0); try { - assetList2.getAssetIssue(0); + assertNotNull(assetList2.getAssetIssue(0)); } catch (Exception e) { Assert.assertTrue("AssetIssueList2 size should be 0", true); } @@ -611,7 +586,7 @@ public void testChainParameters() { }); - System.out.printf(builder.build().toString()); + System.out.print(builder.build()); } @Test @@ -642,12 +617,8 @@ public void testGetDelegatedResource() { delegatedResourceList.getDelegatedResource(0).getFrozenBalanceForBandwidth()); Assert.assertEquals(0L, delegatedResourceList.getDelegatedResource(0).getExpireTimeForBandwidth()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); } catch (Exception e) { - Assert.assertEquals(false, true); + Assert.fail(); } } @@ -755,6 +726,12 @@ public void testGetDelegatedResourceV2() { Protocol.Account account = Protocol.Account.newBuilder() .setAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build(); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addAssetV2("testv2".getBytes(), 1L); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + wallet.getAccount(account); wallet.getProposalList(); wallet.getWitnessList(); @@ -816,7 +793,19 @@ public void testGetCanDelegatedMaxSizeBandWidth() { ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), BANDWIDTH.getNumber()); Assert.assertEquals(initBalance - 280L, message.getMaxSize()); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + @Test + public void testGetCanDelegatedMaxSizeBandWidth2() { + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(86401); + freezeBandwidthForOwner(); + GrpcAPI.CanDelegatedMaxSizeResponseMessage message = wallet.getCanDelegatedMaxSize( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + BANDWIDTH.getNumber()); + Assert.assertEquals(initBalance - 284L, message.getMaxSize()); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); } @Test @@ -1071,5 +1060,17 @@ public void testEstimateEnergyOutOfTime() { Assert.assertTrue(true); } } + + @Test + public void testListNodes() { + try { + wallet.listNodes(); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + Args.getInstance().setP2pDisable(true); + GrpcAPI.NodeList nodeList = wallet.listNodes(); + assertEquals(0, nodeList.getNodesList().size()); + } } diff --git a/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java index ab0847ff072..888e13f1ae6 100644 --- a/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java @@ -1,30 +1,23 @@ package org.tron.core.actuator; +import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -37,9 +30,8 @@ import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; @Slf4j -public class AccountPermissionUpdateActuatorTest { +public class AccountPermissionUpdateActuatorTest extends BaseTest { - private static final String dbPath = "output_transfer_test"; private static final String OWNER_ADDRESS; private static final String WITNESS_ADDRESS; private static final String KEY_ADDRESS; @@ -58,14 +50,10 @@ public class AccountPermissionUpdateActuatorTest { private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String KEY_ADDRESS_INVALID = "bbbb"; - public static Application AppT; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_account_permission_update_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "8CFC572CC20CA18B636BDD93B4FB15EA84CC2B4E"; KEY_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -98,35 +86,14 @@ public class AccountPermissionUpdateActuatorTest { .setWeight(KEY_WEIGHT).build(); } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); - dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); + dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); + AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), ByteString.copyFromUtf8("owner"), AccountType.Normal); @@ -199,27 +166,23 @@ private void processAndCheckInvalid(AccountPermissionUpdateActuator actuator, actuator.execute(ret); fail(failMsg); - } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); + } catch (ContractValidateException | RuntimeException e) { + Assert.assertTrue(true); Assert.assertEquals(expectedMsg, e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); - } catch (RuntimeException e) { - Assert.assertTrue(e instanceof RuntimeException); - Assert.assertEquals(expectedMsg, e.getMessage()); + Assert.fail(); } } @Test public void successUpdatePermissionKey() { - String ownerAddress = OWNER_ADDRESS; String keyAddress = KEY_ADDRESS; // step 1, init addDefaultPermission(); // step2, check init data - byte[] owner_name_array = ByteArray.fromHexString(ownerAddress); + byte[] owner_name_array = ByteArray.fromHexString(OWNER_ADDRESS); ByteString address = ByteString.copyFrom(owner_name_array); AccountCapsule owner = dbManager.getAccountStore().get(owner_name_array); @@ -227,7 +190,7 @@ public void successUpdatePermissionKey() { Permission activePermission = AccountCapsule.createDefaultActivePermission(address, dbManager.getDynamicPropertiesStore()); - Assert.assertEquals(owner.getInstance().getActivePermissionCount(), 1); + Assert.assertEquals(1, owner.getInstance().getActivePermissionCount()); Permission ownerPermission1 = owner.getInstance().getOwnerPermission(); Permission activePermission1 = owner.getInstance().getActivePermission(0); @@ -274,21 +237,19 @@ public void successUpdatePermissionKey() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); // step 4, check result after update operation owner = dbManager.getAccountStore().get(owner_name_array); - Assert.assertEquals(owner.getInstance().getActivePermissionCount(), 1); + Assert.assertEquals(1, owner.getInstance().getActivePermissionCount()); ownerPermission1 = owner.getInstance().getOwnerPermission(); activePermission1 = owner.getInstance().getActivePermission(0); Assert.assertEquals(ownerPermission1, ownerPermission); Assert.assertEquals(activePermission1, activePermission); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -329,8 +290,7 @@ public void invalidTransactionResultCapsule() { AccountPermissionUpdateActuator actuator = new AccountPermissionUpdateActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(OWNER_ADDRESS)); - TransactionResultCapsule ret = null; - processAndCheckInvalid(actuator, ret, "TransactionResultCapsule is null", + processAndCheckInvalid(actuator, null, "TransactionResultCapsule is null", "TransactionResultCapsule is null"); } @@ -398,7 +358,7 @@ public void activeToMany() { for (int i = 0; i <= 8; i++) { activeList.add(activePermission); } - + assertNotNull(activeList); AccountPermissionUpdateActuator actuator = new AccountPermissionUpdateActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(address, ownerPermission, null, null)); @@ -964,12 +924,12 @@ public void checkAvailableContractTypeCorrespondingToCode() { // 7fff1fc0037e0000000000000000000000000000000000000000000000000000, // and it should call the addSystemContractAndSetPermission to add new contract // type - // When you add a new contact, you can add its to contractType, + // When you add a new contact, you can add it to contractType, // as '|| contractType = ContractType.XXX', // and you will get the value from the output, // then update the value to checkAvailableContractType // and checkActiveDefaultOperations - String validContractType = "7fff1fc0037ef807000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0037ef80f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -996,7 +956,7 @@ public void checkActiveDefaultOperationsCorrespondingToCode() { // 7fff1fc0033e0000000000000000000000000000000000000000000000000000, // and it should call the addSystemContractAndSetPermission to add new contract // type - String validContractType = "7fff1fc0033ef807000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0033ef80f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -1019,7 +979,7 @@ public void checkActiveDefaultOperationsCorrespondingToCode() { @Test public void checkAvailableContractType() { - String validContractType = "7fff1fc0037ef907000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0037ef90f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -1040,7 +1000,7 @@ public void checkAvailableContractType() { @Test public void checkActiveDefaultOperations() { - String validContractType = "7fff1fc0033ef907000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0033ef90f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { diff --git a/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java b/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java index fe17d7ae7c4..3ad6aa1d6dd 100644 --- a/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java @@ -1,59 +1,33 @@ package org.tron.core.actuator; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j(topic = "actuator") -public class ActuatorConstantTest { - - private static final String dbPath = "output_actuatorConstant_test"; - public static Application AppT; - private static TronApplicationContext context; +public class ActuatorConstantTest extends BaseTest { /** * Init . */ @BeforeClass public static void init() { + dbPath = "output_actuatorConstant_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @Test - public void variablecheck() { + public void variableCheck() { ActuatorConstant actuator = new ActuatorConstant(); Assert.assertEquals("Account[", actuator.ACCOUNT_EXCEPTION_STR); Assert.assertEquals("Witness[", actuator.WITNESS_EXCEPTION_STR); Assert.assertEquals("Proposal[", actuator.PROPOSAL_EXCEPTION_STR); Assert.assertEquals("] not exists", actuator.NOT_EXIST_STR); - Assert.assertTrue(actuator instanceof ActuatorConstant); } } diff --git a/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java index 1fc858f0804..17cf0e2286c 100755 --- a/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java @@ -4,31 +4,24 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -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.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -38,9 +31,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply; @Slf4j -public class AssetIssueActuatorTest { +public class AssetIssueActuatorTest extends BaseTest { - private static final String dbPath = "output_assetIssue_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_SECOND; private static final String NAME = "trx-my"; @@ -50,44 +42,18 @@ public class AssetIssueActuatorTest { private static final String DESCRIPTION = "myCoin"; private static final String URL = "tron-my.com"; private static final String ASSET_NAME_SECOND = "asset_name2"; - private static TronApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; private static long now = 0; private static long startTime = 0; private static long endTime = 0; static { + dbPath = "output_assetIssue_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ADDRESS_SECOND = Wallet .getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java new file mode 100644 index 00000000000..fcc545a0fc2 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java @@ -0,0 +1,207 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.fail; +import static org.tron.protos.Protocol.Transaction.Result.code.SUCESS; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +@Slf4j +public class CancelAllUnfreezeV2ActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + + static { + dbPath = "output_cancel_all_unfreeze_v2_test"; + Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + @Before + public void setUp() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + } + + @Test + public void testCancelAllUnfreezeV2() { + long now = System.currentTimeMillis(); + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 1000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 2000000L, -1); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 3000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 4000000L, 100); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, 100); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + + assertEquals(SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + Map cancelUnfreezeV2AmountMap = ret.getInstance() + .getCancelUnfreezeV2AmountMap(); + assertEquals(2000000L, ret.getInstance().getWithdrawExpireAmount()); + assertEquals(0, owner.getUnfrozenV2List().size()); + assertEquals(8000000L, cancelUnfreezeV2AmountMap.get("BANDWIDTH").longValue()); + assertEquals(8000000L, cancelUnfreezeV2AmountMap.get("ENERGY").longValue()); + assertEquals(0, cancelUnfreezeV2AmountMap.get("TRON_POWER").longValue()); + } catch (ContractValidateException | ContractExeException e) { + fail(); + } + } + + @Test + public void testNullTransactionResultCapsule() { + long now = System.currentTimeMillis(); + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 1000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 2000000L, -1); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 3000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 4000000L, 100); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, 100); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + try { + actuator.validate(); + } catch (ContractValidateException e) { + fail(); + } + assertThrows(ActuatorConstant.TX_RESULT_NULL, + RuntimeException.class, () -> actuator.execute(null)); + } + + @Test + public void testInvalidOwnerAddress() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2ContractInvalidAddress()); + assertThrows("Invalid address", ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidOwnerAccount() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2ContractInvalidAccount()); + assertThrows("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidOwnerUnfreezeV2List() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + assertThrows("no unfreezeV2 list to cancel", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidCancelAllUnfreezeV2Contract() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(null); + assertThrows(ActuatorConstant.CONTRACT_NOT_EXIST, + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidAccountStore() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(null).setAny(getCancelAllUnfreezeV2Contract()); + assertThrows(ActuatorConstant.STORE_NOT_EXIST, + ContractValidateException.class, actuator::validate); + } + + @Test + public void testSupportAllowCancelAllUnfreezeV2() { + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + assertThrows( + "Not support CancelAllUnfreezeV2 transaction, need to be opened by the committee", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testErrorContract() { + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getErrorContract()); + assertThrows( + "contract type error, expected type [CancelAllUnfreezeV2Contract], " + + "real type[WithdrawExpireUnfreezeContract]", + ContractValidateException.class, actuator::validate); + } + + private Any getCancelAllUnfreezeV2Contract() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } + + private Any getErrorContract() { + return Any.pack(BalanceContract.WithdrawExpireUnfreezeContract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } + + private Any getCancelAllUnfreezeV2ContractInvalidAddress() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS_INVALID))).build()); + } + + private Any getCancelAllUnfreezeV2ContractInvalidAccount() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ACCOUNT_INVALID))).build() + ); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java index de6a426f1ef..1f6571e8868 100644 --- a/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java @@ -1,29 +1,23 @@ package org.tron.core.actuator; import static junit.framework.TestCase.fail; -import static stest.tron.wallet.common.client.utils.PublicMethed.jsonStr2Abi; +import static org.tron.common.utils.PublicMethod.jsonStr2Abi; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -32,11 +26,9 @@ import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; - @Slf4j -public class ClearABIContractActuatorTest { +public class ClearABIContractActuatorTest extends BaseTest { - private static final String dbPath = "output_clearabicontract_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -49,12 +41,10 @@ public class ClearABIContractActuatorTest { "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\"" + ":\"constructor\"}]"); private static final ABI TARGET_ABI = ABI.getDefaultInstance(); - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_clearabicontract_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -62,34 +52,12 @@ public class ClearABIContractActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); // address in accountStore and the owner of contract AccountCapsule accountCapsule = new AccountCapsule( diff --git a/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java index 11c8f7754fc..11f68c0b8bb 100755 --- a/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java @@ -4,24 +4,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -30,19 +24,16 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class CreateAccountActuatorTest { +public class CreateAccountActuatorTest extends BaseTest { - private static final String dbPath = "output_CreateAccount_test"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; private static final String INVALID_ACCOUNT_ADDRESS; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_CreateAccount_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -50,32 +41,6 @@ public class CreateAccountActuatorTest { INVALID_ACCOUNT_ADDRESS = Wallet.getAddressPreFixString() + "12344500882809695a8a687866"; } - /** - * 548794500882809695a8a687866e76d4271a1abc Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ 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 df7d7436f6a..b20d55fd983 100644 --- a/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java @@ -1,87 +1,65 @@ package org.tron.core.actuator; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +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.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract; import org.tron.protos.contract.BalanceContract.DelegateResourceContract; -import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class DelegateResourceActuatorTest { +public class DelegateResourceActuatorTest extends BaseTest { - private static final String dbPath = "output_delegate_resource_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; - private static Manager dbManager; - private static final TronApplicationContext context; static { + dbPath = "output_delegate_resource_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); - dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); AccountCapsule ownerCapsule = @@ -138,18 +116,40 @@ private Any getLockedDelegateContractForBandwidth(String ownerAddress, String re .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiveAddress))) .setBalance(unfreezeBalance) - .setResource(ResourceCode.BANDWIDTH) + .setResource(BANDWIDTH) .setLock(lock) .build()); } + private Any getMaxDelegateLockPeriodContractForBandwidth(long unfreezeBalance, long lockPeriod) { + return Any.pack(DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(BANDWIDTH) + .setLock(true) + .setLockPeriod(lockPeriod) + .build()); + } + + private Any getMaxDelegateLockPeriodContractForEnergy(long unfreezeBalance, long lockPeriod) { + return Any.pack(DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(ENERGY) + .setLock(true) + .setLockPeriod(lockPeriod) + .build()); + } + private Any getDelegateContractForCpu(long unfreezeBalance) { return Any.pack( DelegateResourceContract.newBuilder() .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) .setBalance(unfreezeBalance) - .setResource(ResourceCode.ENERGY) + .setResource(ENERGY) .build()); } @@ -159,7 +159,7 @@ private Any getDelegateContractForTronPower(long unfreezeBalance) { .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) .setBalance(unfreezeBalance) - .setResource(ResourceCode.TRON_POWER) + .setResource(TRON_POWER) .build()); } @@ -177,12 +177,12 @@ public void testDelegateResourceWithNoFreeze() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(); + fail(); } actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( @@ -190,13 +190,13 @@ public void testDelegateResourceWithNoFreeze() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -220,16 +220,15 @@ public void testDelegateBandwidthWithUsage() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } - @Test public void testDelegateCpuWithUsage() { freezeCpuForOwner(); @@ -250,13 +249,13 @@ public void testDelegateCpuWithUsage() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals( + assertEquals( "delegateBalance must be less than available FreezeEnergyV2 balance", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -282,9 +281,9 @@ public void testDelegateResourceWithContractAddress() { actuator.validate(); actuator.execute(ret); } catch (ContractValidateException e) { - Assert.assertEquals("Do not allow delegate resources to contract addresses", e.getMessage()); + assertEquals("Do not allow delegate resources to contract addresses", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -301,9 +300,9 @@ public void testDelegateResourceToSelf() { actuator.validate(); actuator.execute(ret); } catch (ContractValidateException e) { - Assert.assertEquals("receiverAddress must not be the same as ownerAddress", e.getMessage()); + assertEquals("receiverAddress must not be the same as ownerAddress", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -322,48 +321,48 @@ public void testDelegateResourceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); - Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(initBalance - delegateBalance, + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(initBalance - delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); - Assert.assertEquals(initBalance, ownerCapsule.getTronPower()); + assertEquals(initBalance, ownerCapsule.getTronPower()); AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); - Assert.assertEquals(delegateBalance, + assertEquals(delegateBalance, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); - Assert.assertEquals(0L, receiverCapsule.getTronPower()); + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + assertEquals(0L, receiverCapsule.getTronPower()); DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() .get(DelegatedResourceCapsule .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), ByteArray.fromHexString(RECEIVER_ADDRESS), false)); - Assert.assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); - Assert.assertEquals(totalNetWeightBefore, totalNetWeightAfter); + assertEquals(totalNetWeightBefore, totalNetWeightAfter); //check DelegatedResourceAccountIndex DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(owner); - Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); - Assert.assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); - Assert.assertTrue(ownerIndexCapsule.getToAccountsList() + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule receiveCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(receiver); - Assert.assertEquals(0, receiveCapsule.getToAccountsList().size()); - Assert.assertEquals(1, receiveCapsule.getFromAccountsList().size()); - Assert.assertTrue(receiveCapsule.getFromAccountsList() + assertEquals(0, receiveCapsule.getToAccountsList().size()); + assertEquals(1, receiveCapsule.getFromAccountsList().size()); + assertTrue(receiveCapsule.getFromAccountsList() .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); } catch (ContractValidateException | ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -383,22 +382,23 @@ public void testLockedDelegateResourceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); - Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(initBalance - delegateBalance, + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(initBalance - delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); - Assert.assertEquals(initBalance, ownerCapsule.getTronPower()); + assertEquals(initBalance, ownerCapsule.getTronPower()); AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); - Assert.assertEquals(delegateBalance, + assertEquals(delegateBalance, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); - Assert.assertEquals(0L, receiverCapsule.getTronPower()); + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + assertEquals(0L, receiverCapsule.getTronPower()); + //check DelegatedResource DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() .get(DelegatedResourceCapsule .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), @@ -410,28 +410,181 @@ public void testLockedDelegateResourceForBandwidth() { Assert.assertNull(delegatedResourceCapsule); Assert.assertNotNull(lockedResourceCapsule); Assert.assertNotEquals(0, lockedResourceCapsule.getExpireTimeForBandwidth()); - Assert.assertEquals(delegateBalance, lockedResourceCapsule.getFrozenBalanceForBandwidth()); + assertEquals(delegateBalance, lockedResourceCapsule.getFrozenBalanceForBandwidth()); long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); - Assert.assertEquals(totalNetWeightBefore, totalNetWeightAfter); + assertEquals(totalNetWeightBefore, totalNetWeightAfter); //check DelegatedResourceAccountIndex DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(owner); - Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); - Assert.assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); - Assert.assertTrue(ownerIndexCapsule.getToAccountsList() + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule receiveCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(receiver); - Assert.assertEquals(0, receiveCapsule.getToAccountsList().size()); - Assert.assertEquals(1, receiveCapsule.getFromAccountsList().size()); - Assert.assertTrue(receiveCapsule.getFromAccountsList() + assertEquals(0, receiveCapsule.getToAccountsList().size()); + assertEquals(1, receiveCapsule.getFromAccountsList().size()); + assertTrue(receiveCapsule.getFromAccountsList() .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); } catch (ContractValidateException | ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); + } + } + + @Test + public void testMaxDelegateLockPeriodForBandwidthWrongLockPeriod1() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(86401); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 370 * 24 * 3600)); + assertThrows("The lock period of delegate resources cannot exceed 1 year!", + ContractValidateException.class, actuator::validate); + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testMaxDelegateLockPeriodForBandwidthWrongLockPeriod2() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 30)); + assertThrows("The lock period for bandwidth this time cannot be less than the remaining" + + " time[60000s] of the last lock period for bandwidth!", + ContractValidateException.class, actuator1::validate); + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testMaxDelegateLockPeriodForBandwidth() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(50_000L); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret1 = new TransactionResultCapsule(); + try { + actuator1.validate(); + actuator1.execute(ret1); + assertEquals(code.SUCESS, ret1.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), true)); + long expireTimeForBandwidth = lockedResourceCapsule.getExpireTimeForBandwidth(); + assertEquals(50_000L + 60 * 3 * 1000, expireTimeForBandwidth); + assertTrue(expireTimeForBandwidth > 60_000); + } + + @Test + public void testMaxDelegateLockPeriodForEnergy() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(50_000L); + freezeCpuForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret1 = new TransactionResultCapsule(); + try { + actuator1.validate(); + actuator1.execute(ret1); + assertEquals(code.SUCESS, ret1.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); } + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), true)); + assertTrue(lockedResourceCapsule.getExpireTimeForEnergy() > 60_000); + } + + @Test + public void testMaxDelegateLockPeriodForEnergyWrongLockPeriod2() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + freezeCpuForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 30)); + assertThrows("The lock period for energy this time cannot be less than the remaining" + + " time[60000s] of the last lock period for energy!", + ContractValidateException.class, actuator1::validate); } @Test @@ -449,53 +602,50 @@ public void testDelegateResourceForCpu() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); - Assert.assertEquals(initBalance, ownerCapsule.getBalance()); - Assert.assertEquals(0L, ownerCapsule.getFrozenBalance()); - Assert.assertEquals(0L, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); - Assert.assertEquals(initBalance, ownerCapsule.getTronPower()); + assertEquals(initBalance, ownerCapsule.getBalance()); + assertEquals(0L, ownerCapsule.getFrozenBalance()); + assertEquals(0L, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + assertEquals(initBalance, ownerCapsule.getTronPower()); AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); - Assert.assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); - Assert.assertEquals(delegateBalance, + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(delegateBalance, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); - Assert.assertEquals(0L, receiverCapsule.getTronPower()); + assertEquals(0L, receiverCapsule.getTronPower()); DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); - Assert.assertEquals(0L, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); - Assert.assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForEnergy()); + assertEquals(0L, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForEnergy()); long totalEnergyWeightAfter = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); - Assert.assertEquals(totalEnergyWeightBefore, totalEnergyWeightAfter); + assertEquals(totalEnergyWeightBefore, totalEnergyWeightAfter); //check DelegatedResourceAccountIndex DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(owner); - Assert - .assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); - Assert.assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); - Assert.assertTrue(ownerIndexCapsule.getToAccountsList() + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() .contains(ByteString.copyFrom(receiver))); DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager .getDelegatedResourceAccountIndexStore().getV2Index(receiver); - Assert - .assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); - Assert - .assertEquals(1, + assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + assertEquals(1, receiverIndexCapsule.getFromAccountsList().size()); - Assert.assertTrue(receiverIndexCapsule.getFromAccountsList() + assertTrue(receiverIndexCapsule.getFromAccountsList() .contains(ByteString.copyFrom(owner))); } catch (ContractValidateException | ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -510,11 +660,11 @@ public void delegateLessThanZero() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("delegateBalance must be more than 1TRX", e.getMessage()); + assertEquals("delegateBalance must be more than 1TRX", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -528,12 +678,12 @@ public void delegateTronPower() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]", + assertEquals("ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -548,12 +698,12 @@ public void delegateMoreThanBalance() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", + assertEquals("delegateBalance must be less than available FreezeBandwidthV2 balance", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -568,15 +718,25 @@ public void invalidOwnerAddress() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("Invalid address", e.getMessage()); + assertEquals("Invalid address", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } + @Test + public void invalidReceiverAddress() { + freezeBandwidthForOwner(); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, OWNER_ADDRESS_INVALID, 1_000_000_000L)); + assertThrows("Invalid receiverAddress", ContractValidateException.class, actuator::validate); + } + @Test public void invalidOwnerAccount() { DelegateResourceActuator actuator = new DelegateResourceActuator(); @@ -588,12 +748,12 @@ public void invalidOwnerAccount() { try { actuator.validate(); actuator.execute(ret); - Assert.fail("cannot run here."); + fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", + assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", e.getMessage()); } catch (ContractExeException e) { - Assert.fail(e.getMessage()); + fail(e.getMessage()); } } @@ -618,4 +778,48 @@ public void commonErrorCheck() { actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); actuatorTest.nullDBManger(); } + + @Test + public void testSupportDelegateResource() { + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(0); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, + RECEIVER_ADDRESS, + 1_000_000_000L)); + assertThrows( + "No support for resource delegate", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testSupportUnfreezeDelay() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, + RECEIVER_ADDRESS, + 1_000_000_000L)); + assertThrows( + "Not support Delegate resource transaction, need to be opened by the committee", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testErrorContract() { + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getErrorContract()); + assertThrows( + "contract type error, expected type [DelegateResourceContract], " + + "real type[WithdrawExpireUnfreezeContract]", + ContractValidateException.class, actuator::validate); + } + + private Any getErrorContract() { + return Any.pack(BalanceContract.WithdrawExpireUnfreezeContract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } } diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java index 51f658bcbb4..f37016845d4 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java @@ -4,27 +4,21 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -36,53 +30,24 @@ @Slf4j -public class ExchangeCreateActuatorTest { +public class ExchangeCreateActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ExchangeCreate_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -446,8 +411,7 @@ public void sameTokenNameOpenSuccessExchangeCreate() { Assert.assertEquals(id, exchangeCapsuleV2.getID()); Assert.assertEquals(1000000, exchangeCapsuleV2.getCreateTime()); - Assert - .assertTrue(Arrays.equals(firstTokenId.getBytes(), exchangeCapsuleV2.getFirstTokenId())); + Assert.assertArrayEquals(firstTokenId.getBytes(), exchangeCapsuleV2.getFirstTokenId()); Assert.assertEquals(firstTokenId, ByteArray.toStr(exchangeCapsuleV2.getFirstTokenId())); Assert.assertEquals(firstTokenBalance, exchangeCapsuleV2.getFirstTokenBalance()); Assert.assertEquals(secondTokenId, ByteArray.toStr(exchangeCapsuleV2.getSecondTokenId())); diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java index 28d699a26e0..49a80fd3253 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java @@ -5,27 +5,21 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -37,53 +31,24 @@ @Slf4j -public class ExchangeInjectActuatorTest { +public class ExchangeInjectActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeInject_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ExchangeInject_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java index c3381da72df..dad6b24e03e 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java @@ -5,28 +5,22 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import junit.framework.TestCase; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -38,53 +32,24 @@ @Slf4j -public class ExchangeTransactionActuatorTest { +public class ExchangeTransactionActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeTransaction_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ExchangeTransaction_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java index 78b0c18294a..ad08b49c9ee 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java @@ -5,28 +5,22 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import junit.framework.TestCase; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -38,53 +32,24 @@ @Slf4j -public class ExchangeWithdrawActuatorTest { +public class ExchangeWithdrawActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeWithdraw_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ExchangeWithdraw_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** 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 3494ddb0624..abcaf538e93 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java @@ -5,18 +5,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Utils; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; @@ -25,10 +21,8 @@ import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -38,52 +32,23 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class FreezeBalanceActuatorTest { +public class FreezeBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_freeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_freeze_balance_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ 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 1296886637d..082338df753 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java @@ -5,25 +5,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; 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.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -32,58 +26,32 @@ import org.tron.protos.contract.BalanceContract; import org.tron.protos.contract.Common.ResourceCode; - - @Slf4j -public class FreezeBalanceV2ActuatorTest { +public class FreezeBalanceV2ActuatorTest extends BaseTest { - private static final String dbPath = "output_freeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_freeze_balance_v2_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); - dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFromUtf8("owner"), diff --git a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java index ec6404b47a1..a9daf0871b1 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java @@ -4,17 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -25,9 +21,7 @@ import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -46,9 +40,8 @@ @Slf4j -public class MarketCancelOrderActuatorTest { +public class MarketCancelOrderActuatorTest extends BaseTest { - private static final String dbPath = "output_MarketCancelOrder_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -58,12 +51,10 @@ public class MarketCancelOrderActuatorTest { private static final String TOKEN_ID_ONE = String.valueOf(1L); private static final String TOKEN_ID_TWO = String.valueOf(2L); private static final String TRX = "_"; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_MarketCancelOrder_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -73,37 +64,16 @@ public class MarketCancelOrderActuatorTest { } /** - * Init data. + * create temp Capsule test need. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void initTest() { dbManager.getDynamicPropertiesStore().saveAllowMarketTransaction(1L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** - * create temp Capsule test need. - */ - @Before - public void initTest() { byte[] ownerAddressFirstBytes = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); byte[] ownerAddressSecondBytes = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); diff --git a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java index cf654af891d..587a6b5aacd 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java @@ -4,18 +4,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -26,9 +22,7 @@ import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -46,9 +40,8 @@ @Slf4j -public class MarketSellAssetActuatorTest { +public class MarketSellAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_MarketSellAsset_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -58,12 +51,10 @@ public class MarketSellAssetActuatorTest { private static final String TOKEN_ID_ONE = String.valueOf(1L); private static final String TOKEN_ID_TWO = String.valueOf(2L); private static final String TRX = "_"; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_MarketSellAsset_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -73,37 +64,16 @@ public class MarketSellAssetActuatorTest { } /** - * Init data. + * create temp Capsule test need. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void initTest() { dbManager.getDynamicPropertiesStore().saveAllowMarketTransaction(1L); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** - * create temp Capsule test need. - */ - @Before - public void initTest() { byte[] ownerAddressFirstBytes = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); byte[] ownerAddressSecondBytes = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); diff --git a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java index 168725f9634..0bcfbc8820f 100755 --- a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java @@ -2,27 +2,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -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.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -31,10 +22,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -public class ParticipateAssetIssueActuatorTest { +public class ParticipateAssetIssueActuatorTest extends BaseTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private static final String dbPath = "output_participateAsset_test"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; private static final String TO_ADDRESS_2; @@ -49,14 +38,11 @@ public class ParticipateAssetIssueActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; private static long AMOUNT = TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM; static { + dbPath = "output_participateAsset_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1234"; TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TO_ADDRESS_2 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e048892"; @@ -64,36 +50,13 @@ public class ParticipateAssetIssueActuatorTest { NOT_EXIT_ADDRESS = Wallet.getAddressPreFixString() + "B56446E617E924805E4D6CA021D341FEF6E2013B"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - - chainBaseManager.getDynamicPropertiesStore().saveTokenIdNum(1000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + chainBaseManager.getDynamicPropertiesStore().saveTokenIdNum(1000000); + AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFromUtf8("owner"), diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java index 5ca4d7abfcf..484c6666941 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java @@ -4,17 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -22,9 +18,7 @@ import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -35,10 +29,8 @@ import org.tron.protos.contract.ProposalContract; @Slf4j +public class ProposalApproveActuatorTest extends BaseTest { -public class ProposalApproveActuatorTest { - - private static final String dbPath = "output_ProposalApprove_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -46,12 +38,10 @@ public class ProposalApproveActuatorTest { private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ProposalApprove_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -60,28 +50,6 @@ public class ProposalApproveActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java index 56bf9504730..1e95911884c 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java @@ -4,26 +4,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -33,10 +27,8 @@ import org.tron.protos.contract.ProposalContract.ProposalCreateContract; @Slf4j +public class ProposalCreateActuatorTest extends BaseTest { -public class ProposalCreateActuatorTest { - - private static final String dbPath = "output_ProposalCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -44,43 +36,16 @@ public class ProposalCreateActuatorTest { private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ProposalCreate_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java index e8d7829f90c..63e5758a907 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java @@ -4,17 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -22,9 +18,7 @@ import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -35,10 +29,8 @@ import org.tron.protos.contract.ProposalContract; @Slf4j +public class ProposalDeleteActuatorTest extends BaseTest { -public class ProposalDeleteActuatorTest { - - private static final String dbPath = "output_ProposalApprove_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -46,12 +38,10 @@ public class ProposalDeleteActuatorTest { private static final String URL = "https://tron.network"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_ProposalDelete_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -60,28 +50,6 @@ public class ProposalDeleteActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java index 018ae6401bc..0b4311ca46f 100644 --- a/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java @@ -2,23 +2,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -27,46 +21,21 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class SetAccountIdActuatorTest { +public class SetAccountIdActuatorTest extends BaseTest { - private static final String dbPath = "output_setaccountid_test"; private static final String ACCOUNT_NAME = "ownertest"; private static final String ACCOUNT_NAME_1 = "ownertest1"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_1; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_setaccountid_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_1 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java index 5bac3effbef..5e7d33832b4 100755 --- a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java @@ -1,16 +1,16 @@ package org.tron.core.actuator; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.core.Constant; @@ -22,15 +22,12 @@ import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.PermissionException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.exception.ZksnarkException; import org.tron.core.services.http.FullNodeHttpApiService; -import org.tron.core.utils.TransactionUtil; import org.tron.core.zen.ZenTransactionBuilder; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; @@ -44,17 +41,14 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.ShieldContract.PedersenHash; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; -import stest.tron.wallet.common.client.utils.TransactionUtils; @Slf4j -public class ShieldedTransferActuatorTest { +public class ShieldedTransferActuatorTest extends BaseTest { - private static final String dbPath = "output_shield_transfer_test"; private static final String PUBLIC_ADDRESS_ONE; private static final String ADDRESS_ONE_PRIVATE_KEY; private static final String PUBLIC_ADDRESS_TWO; private static final String ADDRESS_TWO_PRIVATE_KEY; - private static final String PUBLIC_ADDRESS_OFF_LINE; private static final long AMOUNT = 100000000L; private static final long OWNER_BALANCE = 9999999000000L; private static final long TO_BALANCE = 100001000000L; @@ -69,22 +63,20 @@ public class ShieldedTransferActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static Wallet wallet; - private static Manager dbManager; - private static TronApplicationContext context; - private static TransactionUtil transactionUtil; + + @Resource + private Wallet wallet; static { + dbPath = "output_shield_transfer_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - PUBLIC_ADDRESS_ONE = - Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; - ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; + ADDRESS_ONE_PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); + PUBLIC_ADDRESS_ONE = PublicMethod.getHexAddressByPrivateKey(ADDRESS_ONE_PRIVATE_KEY); + + ADDRESS_TWO_PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); PUBLIC_ADDRESS_TWO = - Wallet.getAddressPreFixString() + "8ba2aaae540c642e44e3bed5522c63bbc21fff92"; - ADDRESS_TWO_PRIVATE_KEY = "e4e0edd6bff7b353dfc69a590721e902e6915c5e3e87d36dcb567a9716304720"; - PUBLIC_ADDRESS_OFF_LINE = - Wallet.getAddressPreFixString() + "7bcb781f4743afaacf9f9528f3ea903b3782339f"; + PublicMethod.getHexAddressByPrivateKey(ADDRESS_TWO_PRIVATE_KEY); + DEFAULT_OVK = ByteArray.fromHexString( "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); } @@ -95,27 +87,10 @@ public class ShieldedTransferActuatorTest { @BeforeClass public static void init() throws ZksnarkException { Args.setFullNodeAllowShieldedTransaction(true); - wallet = context.getBean(Wallet.class); - transactionUtil = context.getBean(TransactionUtil.class); - dbManager = context.getBean(Manager.class); librustzcashInitZksnarkParams(); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - private static void librustzcashInitZksnarkParams() throws ZksnarkException { + private static void librustzcashInitZksnarkParams() { FullNodeHttpApiService.librustzcashInitZksnarkParams(); } diff --git a/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java index c8f55768910..05aea41e7c7 100644 --- a/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java @@ -5,26 +5,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Date; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -38,9 +32,8 @@ import org.tron.protos.contract.BalanceContract.TransferContract; @Slf4j -public class TransferActuatorTest { +public class TransferActuatorTest extends BaseTest { - private static final String dbPath = "output_transfer_test"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; private static final long AMOUNT = 100; @@ -51,12 +44,10 @@ public class TransferActuatorTest { private static final String OWNER_ACCOUNT_INVALID; private static final String OWNER_NO_BALANCE; private static final String To_ACCOUNT_INVALID; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_transfer_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ACCOUNT_INVALID = @@ -66,32 +57,6 @@ public class TransferActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3422"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java index 440cbc3a4a7..07bb8415068 100755 --- a/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java @@ -20,28 +20,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; - -import java.io.File; - import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -57,9 +49,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; @Slf4j -public class TransferAssetActuatorTest { +public class TransferAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_transferasset_test"; private static final String ASSET_NAME = "trx"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; @@ -79,13 +70,10 @@ public class TransferAssetActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static TronApplicationContext context; - private static Manager dbManager; - private static Any contract; static { + dbPath = "output_transferasset_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; TO_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a146a"; NOT_EXIT_ADDRESS = Wallet.getAddressPreFixString() + "B56446E617E924805E4D6CA021D341FEF6E2013B"; @@ -95,28 +83,6 @@ public class TransferAssetActuatorTest { Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049010"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java index f57c82935e2..82ed6865fb8 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java @@ -6,25 +6,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -34,56 +28,32 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class UnDelegateResourceActuatorTest { +public class UnDelegateResourceActuatorTest extends BaseTest { - private static final String dbPath = "output_unDelegate_resource_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long delegateBalance = 1_000_000_000L; - private static Manager dbManager; - private static final TronApplicationContext context; static { + dbPath = "output_unDelegate_resource_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); - dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, initBalance); @@ -398,6 +368,80 @@ public void testLockedAndUnlockUnDelegateForBandwidth() { } } + + @Test + public void testLockedAndUnlockUnDelegateForBandwidthUsingWindowSizeV2() { + delegateLockedBandwidthForOwner(Long.MAX_VALUE); + delegateBandwidthForOwner(); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(2 * delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, + ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNotNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check DelegatedResource + DelegatedResourceCapsule delegatedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule1); + Assert.assertNotNull(lockedResourceCapsule1); + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(1000000000, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(750000000, ownerCapsule.getNetUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(1000000000, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(250000000, receiverCapsule.getNetUsage()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + } + @Test public void testLockedUnDelegateBalanceForBandwidthInsufficient() { delegateLockedBandwidthForOwner(Long.MAX_VALUE); diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java index 70437a890df..0a624faf113 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java @@ -2,25 +2,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.Account; @@ -32,49 +26,23 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; @Slf4j -public class UnfreezeAssetActuatorTest { +public class UnfreezeAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_unfreeze_asset_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long frozenBalance = 1_000_000_000L; private static final String assetName = "testCoin"; - private static final String assetID = "123456"; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_unfreeze_asset_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ 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 de24f581c04..3f9b999228c 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java @@ -4,18 +4,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -23,9 +19,7 @@ import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -36,54 +30,24 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class UnfreezeBalanceActuatorTest { +public class UnfreezeBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_unfreeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long frozenBalance = 1_000_000_000L; - private static final long smallTatalResource = 100L; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_unfreeze_balance_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ 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 6caa3727a0c..14a6de98606 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java @@ -6,24 +6,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -34,56 +28,32 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class UnfreezeBalanceV2ActuatorTest { +public class UnfreezeBalanceV2ActuatorTest extends BaseTest { - private static final String dbPath = "output_unfreeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long frozenBalance = 1_000_000_000L; - private static Manager dbManager; - private static final TronApplicationContext context; static { + dbPath = "output_unfreeze_balance_v2_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); - dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, initBalance); diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java index 315a045128a..acbb9fb4d0b 100755 --- a/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java @@ -4,23 +4,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -29,46 +23,21 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class UpdateAccountActuatorTest { +public class UpdateAccountActuatorTest extends BaseTest { - private static final String dbPath = "output_updateaccount_test"; private static final String ACCOUNT_NAME = "ownerTest"; private static final String ACCOUNT_NAME_1 = "ownerTest1"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_1; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_updateaccount_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_1 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java index 6bd57c85361..b7583bc335b 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java @@ -4,28 +4,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Date; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -34,9 +26,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; @Slf4j -public class UpdateAssetActuatorTest { +public class UpdateAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_updateAsset_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -46,14 +37,10 @@ public class UpdateAssetActuatorTest { private static final long TOTAL_SUPPLY = 10000L; private static final String DESCRIPTION = "myCoin"; private static final String URL = "tron-my.com"; - private static TronApplicationContext context; - private static Application AppT; - private static Manager dbManager; static { + dbPath = "output_updateAsset_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -61,28 +48,6 @@ public class UpdateAssetActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java index e2ce611c56b..034415e0ef1 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java @@ -4,25 +4,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.DelegationStore; @@ -32,19 +26,16 @@ import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; @Slf4j(topic = "actuator") -public class UpdateBrokerageActuatorTest { +public class UpdateBrokerageActuatorTest extends BaseTest { - private static final String dbPath = "output_updatebrokerageactuator_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_NOTEXIST; private static final String OWNER_ADDRESS_INVALID; private static final int BROKEN_AGE = 10; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_updatebrokerageactuator_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "1234b9367799eaa3197fecb144eb71de1e049123"; @@ -52,34 +43,10 @@ public class UpdateBrokerageActuatorTest { Wallet.getAddressPreFixString() + "354394500882809695a8a687866e7"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - @Before /** * set witness store, account store, dynamic store */ + @Before public void initDB() { // allow dynamic store dbManager.getDynamicPropertiesStore().saveChangeDelegation(1); diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java index 9a662e15834..3703dc74e87 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java @@ -5,28 +5,23 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.TronException; @@ -37,10 +32,8 @@ @Slf4j -//@Ignore -public class UpdateEnergyLimitContractActuatorTest { +public class UpdateEnergyLimitContractActuatorTest extends BaseTest { - private static final String dbPath = "output_updateEnergyLimitContractActuator_test"; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String SMART_CONTRACT_NAME = "smart_contarct"; @@ -49,15 +42,13 @@ public class UpdateEnergyLimitContractActuatorTest { private static final long SOURCE_ENERGY_LIMIT = 10L; private static final long TARGET_ENERGY_LIMIT = 30L; private static final long INVALID_ENERGY_LIMIT = -200L; - private static TronApplicationContext context; - private static Manager dbManager; private static String OWNER_ADDRESS; private static String SECOND_ACCOUNT_ADDRESS; private static String OWNER_ADDRESS_NOTEXIST; static { + dbPath = "output_updateEnergyLimitContractActuator_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } /** @@ -65,40 +56,24 @@ public class UpdateEnergyLimitContractActuatorTest { */ @BeforeClass public static void init() { - dbManager = context.getBean(Manager.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; SECOND_ACCOUNT_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - - byte[] stats = new byte[27]; - Arrays.fill(stats, (byte) 1); - dbManager.getDynamicPropertiesStore() - .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); CommonParameter.getInstance().setBlockNumForEnergyLimit(0); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + dbManager.getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); // address in accountStore and the owner of contract AccountCapsule accountCapsule = new AccountCapsule( diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java index 1113b4b1689..0445f893983 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java @@ -4,25 +4,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -32,9 +26,8 @@ @Slf4j -public class UpdateSettingContractActuatorTest { +public class UpdateSettingContractActuatorTest extends BaseTest { - private static final String dbPath = "output_updatesettingcontract_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -46,12 +39,10 @@ public class UpdateSettingContractActuatorTest { private static final long SOURCE_PERCENT = 10L; private static final long TARGET_PERCENT = 30L; private static final long INVALID_PERCENT = 200L; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_updatesettingcontract_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -59,28 +50,6 @@ public class UpdateSettingContractActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java index ef075f02168..cedd147dbaa 100644 --- a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java @@ -4,16 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; @@ -22,10 +19,8 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -37,9 +32,8 @@ import org.tron.protos.contract.WitnessContract.VoteWitnessContract.Vote; @Slf4j -public class VoteWitnessActuatorTest { +public class VoteWitnessActuatorTest extends BaseTest { - private static final String dbPath = "output_VoteWitness_test"; private static final String ACCOUNT_NAME = "account"; private static final String OWNER_ADDRESS; private static final String WITNESS_NAME = "witness"; @@ -49,14 +43,16 @@ public class VoteWitnessActuatorTest { private static final String WITNESS_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_BALANCENOTSUFFICIENT; - private static TronApplicationContext context; - private static Manager dbManager; - private static MaintenanceManager maintenanceManager; - private static ConsensusService consensusService; + @Resource + private MaintenanceManager maintenanceManager; + @Resource + private ConsensusService consensusService; + + private static boolean consensusStart; static { + dbPath = "output_VoteWitness_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; WITNESS_ADDRESS_NOACCOUNT = @@ -67,31 +63,6 @@ public class VoteWitnessActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - maintenanceManager = context.getBean(MaintenanceManager.class); - consensusService = context.getBean(ConsensusService.class); - consensusService.start(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -120,6 +91,12 @@ public void createCapsule() { dbManager.getAccountStore() .put(ownerAccountFirstCapsule.getAddress().toByteArray(), ownerAccountFirstCapsule); dbManager.getWitnessStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + if (consensusStart) { + return; + } + consensusService.start(); + consensusStart = true; } private Any getContract(String address, String voteaddress, Long value) { @@ -203,7 +180,6 @@ public void InvalidAddress() { actuator.execute(ret); fail("Invalid address"); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid address", e.getMessage()); maintenanceManager.doMaintenance(); WitnessCapsule witnessCapsule = dbManager.getWitnessStore() @@ -300,7 +276,7 @@ public void invalideVoteAddress() { try { actuator.validate(); actuator.execute(ret); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(0, dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)).getVotesList().size()); diff --git a/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java index ef979d8acb9..7010b10657a 100644 --- a/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java @@ -4,26 +4,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.args.Witness; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -33,51 +27,22 @@ import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; @Slf4j -public class WithdrawBalanceActuatorTest { +public class WithdrawBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_withdraw_balance_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long allowance = 32_000_000L; - private static Manager dbManager; - private static TronApplicationContext context; static { + dbPath = "output_withdraw_balance_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java index d3ec771b5fa..1544e546854 100644 --- a/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java @@ -7,25 +7,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -36,54 +30,30 @@ import org.tron.protos.contract.BalanceContract.WithdrawExpireUnfreezeContract; @Slf4j -public class WithdrawExpireUnfreezeActuatorTest { +public class WithdrawExpireUnfreezeActuatorTest extends BaseTest { - private static final String dbPath = "output_withdraw_expire_unfreeze_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "abc"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long allowance = 32_000_000L; - private static Manager dbManager; - private static final TronApplicationContext context; static { + dbPath = "output_withdraw_expire_unfreeze_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); - dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, initBalance); diff --git a/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java index 2c85ae00deb..721d88af2b6 100644 --- a/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java @@ -4,24 +4,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -30,10 +24,8 @@ import org.tron.protos.contract.WitnessContract.WitnessCreateContract; @Slf4j +public class WitnessCreateActuatorTest extends BaseTest { -public class WitnessCreateActuatorTest { - - private static final String dbPath = "output_WitnessCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -42,12 +34,10 @@ public class WitnessCreateActuatorTest { private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_WitnessCreate_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -58,29 +48,6 @@ public class WitnessCreateActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java index bad820cc7bb..31ac6a3cf88 100644 --- a/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java @@ -4,24 +4,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -30,9 +24,8 @@ import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; @Slf4j -public class WitnessUpdateActuatorTest { +public class WitnessUpdateActuatorTest extends BaseTest { - private static final String dbPath = "output_WitnessUpdate_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String OWNER_ADDRESS_NOT_WITNESS; @@ -41,12 +34,10 @@ public class WitnessUpdateActuatorTest { private static final String URL = "https://tron.network"; private static final String NewURL = "https://tron.org"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { + dbPath = "output_WitnessUpdate_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -54,28 +45,6 @@ public class WitnessUpdateActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java index ed19516a608..5de7771dfe2 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java @@ -1,82 +1,55 @@ package org.tron.core.actuator.utils; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.ForkController; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter; import org.tron.core.config.Parameter.ForkBlockVersionEnum; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.utils.ProposalUtil; import org.tron.core.utils.ProposalUtil.ProposalType; @Slf4j(topic = "actuator") -public class ProposalUtilTest { +public class ProposalUtilTest extends BaseTest { - private static final String dbPath = "output_ProposalUtil_test"; private static final long LONG_VALUE = 100_000_000_000_000_000L; private static final String LONG_VALUE_ERROR = "Bad chain parameter value, valid range is [0," + LONG_VALUE + "]"; - public static Application AppT; - private static TronApplicationContext context; - private static Manager dbManager; /** * Init . */ @BeforeClass public static void init() { + dbPath = "output_ProposalUtil_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - AppT = ApplicationFactory.create(context); } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - + @Test public void validProposalTypeCheck() throws ContractValidateException { - Assert.assertEquals(false, ProposalType.contain(4000)); - Assert.assertEquals(false, ProposalType.contain(-1)); - Assert.assertEquals(true, ProposalType.contain(2)); + Assert.assertFalse(ProposalType.contain(4000)); + Assert.assertFalse(ProposalType.contain(-1)); + Assert.assertTrue(ProposalType.contain(2)); - Assert.assertEquals(null, ProposalType.getEnumOrNull(-2)); + Assert.assertNull(ProposalType.getEnumOrNull(-2)); Assert.assertEquals(ProposalType.ALLOW_TVM_SOLIDITY_059, ProposalType.getEnumOrNull(32)); long code = -1; try { ProposalType.getEnum(code); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals("Does not support code : " + code, e.getMessage()); } @@ -88,128 +61,126 @@ public void validProposalTypeCheck() throws ContractValidateException { @Test public void validateCheck() { - ProposalUtil actuatorUtil = new ProposalUtil(); DynamicPropertiesStore dynamicPropertiesStore = null; ForkController forkUtils = ForkController.instance(); long invalidValue = -1; try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ACCOUNT_UPGRADE_COST.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ACCOUNT_UPGRADE_COST.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_ACCOUNT_FEE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_ACCOUNT_FEE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ASSET_ISSUE_FEE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ASSET_ISSUE_FEE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } - long value = 32; try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 3 * 27 * 1000 - 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", @@ -217,9 +188,9 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 24 * 3600 * 1000 + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", @@ -227,9 +198,9 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_CREATION_OF_CONTRACTS.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_CREATION_OF_CONTRACTS] is only allowed to be 1", @@ -239,9 +210,9 @@ public void validateCheck() { dynamicPropertiesStore = dbManager.getDynamicPropertiesStore(); dynamicPropertiesStore.saveRemoveThePowerOfTheGr(1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[REMOVE_THE_POWER_OF_THE_GR] is only allowed to be 1", @@ -250,9 +221,9 @@ public void validateCheck() { dynamicPropertiesStore.saveRemoveThePowerOfTheGr(-1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This proposal has been executed before and is only allowed to be executed once", @@ -260,27 +231,27 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 9); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [10,100]", e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 101); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [10,100]", e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_DELEGATE_RESOURCE.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_DELEGATE_RESOURCE] is only allowed to be 1", e.getMessage()); @@ -288,9 +259,9 @@ public void validateCheck() { dynamicPropertiesStore.saveAllowSameTokenName(1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_TVM_TRANSFER_TRC10] is only allowed to be 1", e.getMessage()); @@ -298,9 +269,9 @@ public void validateCheck() { dynamicPropertiesStore.saveAllowSameTokenName(0); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals("[ALLOW_SAME_TOKEN_NAME] proposal must be approved " + "before [ALLOW_TVM_TRANSFER_TRC10] can be proposed", e.getMessage()); @@ -357,6 +328,10 @@ public void validateCheck() { Assert.assertEquals("Bad chain parameter value, valid range is [0, 1_000_000_000_000L]", e.getMessage()); } + + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.ENERGY_LIMIT.getValue(), stats); + forkUtils.reset(); } @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 a46bf546821..0baaad7c962 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 @@ -1,147 +1,168 @@ package org.tron.core.actuator.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; - -import java.io.File; -import java.io.UnsupportedEncodingException; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +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 com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; +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.AccountType; @Slf4j(topic = "capsule") -public class TransactionUtilTest { +public class TransactionUtilTest extends BaseTest { - private static final String dbPath = "output_transactionUtil_test"; - public static Application AppT; - private static TronApplicationContext context; + private static String OWNER_ADDRESS; /** * Init . */ @BeforeClass public static void init() { + dbPath = "output_transactionUtil_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + @Before + public void setUp() { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(owner), + AccountType.Normal, + 10_000_000_000L); + ownerCapsule.setFrozenForBandwidth(1000000L, 1000000L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); } @Test - public void validAccountNameCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String account = ""; - Assert.assertEquals(true, actuatorUtil.validAccountName(account.getBytes("utf-8"))); + public void validAccountNameCheck() { + StringBuilder account = new StringBuilder(); + assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 200; i++) { - account += (char) ('a' + (i % 26)); + account.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAccountName(account.getBytes("utf-8"))); - account += 'z'; - Assert.assertEquals(false, actuatorUtil.validAccountName(account.getBytes("utf-8"))); + assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); + account.append('z'); + assertFalse(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validAccountIdCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String accountId = ""; - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + public void validAccountIdCheck() { + StringBuilder accountId = new StringBuilder(); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 7; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 26; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = "ab cdefghij"; - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = Character.toString((char) 128) + "abcdefjijk" + Character.toString((char) 129); - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = ""; + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder("ab cdefghij"); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder((char) 128 + "abcdefjijk" + (char) 129); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder(); for (int i = 0; i < 30; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + assertTrue(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validAssetNameCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String assetName = ""; - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); + public void validAssetNameCheck() { + StringBuilder assetName = new StringBuilder(); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 33; i++) { - assetName += (char) ('a' + (i % 26)); + assetName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = "ab cdefghij"; - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = Character.toString((char) 128) + "abcdefjijk" + Character.toString((char) 129); - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = ""; + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder("ab cdefghij"); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder((char) 128 + "abcdefjijk" + (char) 129); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder(); for (int i = 0; i < 20; i++) { - assetName += (char) ('a' + (i % 26)); + assetName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); + assertTrue(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validTokenAbbrNameCheck() throws UnsupportedEncodingException { - - TransactionUtil actuatorUtil = new TransactionUtil(); - String abbrName = ""; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); + public void validTokenAbbrNameCheck() { + StringBuilder abbrName = new StringBuilder(); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 6; i++) { - abbrName += (char) ('a' + (i % 26)); + abbrName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = "a bd"; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = "a" + Character.toString((char) 129) + 'f'; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = ""; + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder("a bd"); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder("a" + (char) 129 + 'f'); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder(); for (int i = 0; i < 5; i++) { - abbrName += (char) ('a' + (i % 26)); + abbrName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); + assertTrue(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void isNumberCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); + public void isNumberCheck() { String number = ""; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "123df34"; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "013"; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "24"; - Assert.assertEquals(true, isNumber(number.getBytes("utf-8"))); + assertTrue(isNumber(number.getBytes(StandardCharsets.UTF_8))); + } + + @Test + public void testEstimateConsumeBandWidthSize() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize = TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, + dbManager.getChainBaseManager()); + assertEquals(275L, estimateConsumeBandWidthSize); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testEstimateConsumeBandWidthSize2() { + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize = TransactionUtil.estimateConsumeBandWidthSize(ownerCapsule, + dbManager.getChainBaseManager()); + assertEquals(277L, estimateConsumeBandWidthSize); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); } } diff --git a/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java b/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java index 3fd3a352a48..952aab1a91d 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java @@ -1,74 +1,38 @@ package org.tron.core.actuator.utils; -import java.io.File; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; import org.tron.core.utils.ZenChainParams; @Slf4j(topic = "capsule") public class ZenChainParamsTest { - private static final String dbPath = "output_zenchainparams_test"; - public static Application AppT; - private static TronApplicationContext context; - - /** - * Init . - */ - @BeforeClass - public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void variableCheck() { - ZenChainParams actuatorUtils = new ZenChainParams(); - Assert.assertEquals(16, actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(1, actuatorUtils.ZC_NOTEPLAINTEXT_LEADING); - Assert.assertEquals(8, actuatorUtils.ZC_V_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_R_SIZE); - Assert.assertEquals(512, actuatorUtils.ZC_MEMO_SIZE); - Assert.assertEquals(11, actuatorUtils.ZC_DIVERSIFIER_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_JUBJUB_POINT_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_JUBJUB_SCALAR_SIZE); + ZenChainParams zenChainParams = new ZenChainParams(); + assertNotNull(zenChainParams); + assertEquals(16, ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(1, ZenChainParams.ZC_NOTEPLAINTEXT_LEADING); + assertEquals(8, ZenChainParams.ZC_V_SIZE); + assertEquals(32, ZenChainParams.ZC_R_SIZE); + assertEquals(512, ZenChainParams.ZC_MEMO_SIZE); + assertEquals(11, ZenChainParams.ZC_DIVERSIFIER_SIZE); + assertEquals(32, ZenChainParams.ZC_JUBJUB_POINT_SIZE); + assertEquals(32, ZenChainParams.ZC_JUBJUB_SCALAR_SIZE); int ZC_ENCPLAINTEXT_SIZE = - actuatorUtils.ZC_NOTEPLAINTEXT_LEADING + actuatorUtils.ZC_DIVERSIFIER_SIZE - + actuatorUtils.ZC_V_SIZE + actuatorUtils.ZC_R_SIZE + actuatorUtils.ZC_MEMO_SIZE; - Assert.assertEquals(ZC_ENCPLAINTEXT_SIZE, actuatorUtils.ZC_ENCPLAINTEXT_SIZE); - int ZC_ENCCIPHERTEXT_SIZE = (actuatorUtils.ZC_ENCPLAINTEXT_SIZE - + actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(ZC_ENCCIPHERTEXT_SIZE, actuatorUtils.ZC_ENCCIPHERTEXT_SIZE); - int ZC_OUTCIPHERTEXT_SIZE = (actuatorUtils.ZC_OUTPLAINTEXT_SIZE - + actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(ZC_OUTCIPHERTEXT_SIZE, actuatorUtils.ZC_OUTCIPHERTEXT_SIZE); - Assert.assertTrue(actuatorUtils instanceof ZenChainParams); + ZenChainParams.ZC_NOTEPLAINTEXT_LEADING + ZenChainParams.ZC_DIVERSIFIER_SIZE + + ZenChainParams.ZC_V_SIZE + ZenChainParams.ZC_R_SIZE + ZenChainParams.ZC_MEMO_SIZE; + assertEquals(ZenChainParams.ZC_ENCPLAINTEXT_SIZE, ZC_ENCPLAINTEXT_SIZE); + int ZC_ENCCIPHERTEXT_SIZE = (ZenChainParams.ZC_ENCPLAINTEXT_SIZE + + ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(ZenChainParams.ZC_ENCCIPHERTEXT_SIZE, ZC_ENCCIPHERTEXT_SIZE); + int ZC_OUTCIPHERTEXT_SIZE = (ZenChainParams.ZC_OUTPLAINTEXT_SIZE + + ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(ZenChainParams.ZC_OUTCIPHERTEXT_SIZE, ZC_OUTCIPHERTEXT_SIZE); } } diff --git a/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java index 6c97848cd70..65aab3e9e7a 100644 --- a/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java @@ -1,34 +1,25 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Key; import org.tron.protos.Protocol.Permission; import org.tron.protos.Protocol.Vote; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -public class AccountCapsuleTest { +public class AccountCapsuleTest extends BaseTest { - private static final String dbPath = "output_accountCapsule_test"; - private static final Manager dbManager; - private static final TronApplicationContext context; private static final String OWNER_ADDRESS; private static final String ASSET_NAME = "trx"; private static final long TOTAL_SUPPLY = 10000L; @@ -45,10 +36,8 @@ public class AccountCapsuleTest { static AccountCapsule accountCapsule; static { + dbPath = "output_accountCapsule_test"; Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "a06a17a49648a8ad32055c06f60fa14ae46df91234"; } @@ -64,13 +53,6 @@ public static void init() { accountCapsuleTest.setBalance(1111L); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - public static byte[] randomBytes(int length) { //generate the random number byte[] result = new byte[length]; @@ -129,9 +111,8 @@ public void AssetAmountTest() { Assert.assertEquals(nameAdd, entry.getKey()); Assert.assertEquals(amountAdd - amountReduce, entry.getValue().longValue()); } - String key = nameAdd; long value = 11L; - boolean addAsssetBoolean = accountCapsuleTest.addAsset(key.getBytes(), value); + boolean addAsssetBoolean = accountCapsuleTest.addAsset(nameAdd.getBytes(), value); Assert.assertFalse(addAsssetBoolean); String keyName = "TokenTest"; @@ -193,9 +174,9 @@ public void sameTokenNameCloseAssertAmountV2test() { dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), 1000L); - Assert.assertEquals(accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue(), 1000L); - Assert.assertEquals(accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), - 1000L); + Assert.assertEquals(1000L, accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue()); + Assert.assertEquals(1000L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //assetBalanceEnoughV2 Assert.assertTrue(accountCapsule.assetBalanceEnoughV2(ByteArray.fromString(ASSET_NAME), @@ -217,10 +198,11 @@ public void sameTokenNameCloseAssertAmountV2test() { Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(ASSET_NAME), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); // 1000-999 +500 - Assert.assertEquals(accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue(), 501L); + Assert.assertEquals(501L, accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue()); Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString("abc"), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); - Assert.assertEquals(accountCapsule.getAssetMapForTest().get("abc").longValue(), 500L); + Assert.assertEquals(500L, + accountCapsule.getAssetMapForTest().get("abc").longValue()); } /** @@ -274,8 +256,8 @@ public void sameTokenNameOpenAssertAmountV2test() { 10000); accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), 1000L); dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); - Assert.assertEquals(accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), - 1000L); + Assert.assertEquals(1000L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //assetBalanceEnoughV2 Assert.assertTrue(accountCapsule.assetBalanceEnoughV2(ByteArray.fromString(String.valueOf(id)), @@ -300,14 +282,14 @@ public void sameTokenNameOpenAssertAmountV2test() { Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(String.valueOf(id)), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); // 1000-999 +500 - Assert.assertEquals(accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), - 501L); + Assert.assertEquals(501L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //abc Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(String.valueOf(id + 1)), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); Assert - .assertEquals(accountCapsule.getAssetV2MapForTest().get(String.valueOf(id + 1)).longValue(), - 500L); + .assertEquals(500L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id + 1)).longValue()); } @Test @@ -319,9 +301,8 @@ public void witnessPermissionTest() { AccountType.Normal, 10000); - Assert.assertTrue( - Arrays.equals(ByteArray.fromHexString(OWNER_ADDRESS), - accountCapsule.getWitnessPermissionAddress())); + Assert.assertArrayEquals(ByteArray.fromHexString(OWNER_ADDRESS), + accountCapsule.getWitnessPermissionAddress()); String witnessPermissionAddress = Wallet.getAddressPreFixString() + "cc6a17a49648a8ad32055c06f60fa14ae46df912cc"; @@ -330,8 +311,7 @@ public void witnessPermissionTest() { .setAddress(ByteString.copyFrom(ByteArray.fromHexString(witnessPermissionAddress))) .build()).build()).build()); - Assert.assertTrue( - Arrays.equals(ByteArray.fromHexString(witnessPermissionAddress), - accountCapsule.getWitnessPermissionAddress())); + Assert.assertArrayEquals(ByteArray.fromHexString(witnessPermissionAddress), + accountCapsule.getWitnessPermissionAddress()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java index 60766a07863..88d67c3a632 100644 --- a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java @@ -2,6 +2,8 @@ import com.google.protobuf.ByteString; import java.io.File; +import java.util.Arrays; + import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; import org.junit.Assert; @@ -9,6 +11,8 @@ import org.junit.Test; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -20,6 +24,9 @@ @Slf4j public class BlockCapsuleTest { + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private LocalWitnesses localWitnesses; + private static BlockCapsule blockCapsule0 = new BlockCapsule(1, Sha256Hash.wrap(ByteString .copyFrom(ByteArray @@ -119,9 +126,15 @@ public void testGetInsHash() { Sha256Hash.wrap(blockCapsule0.getParentHashStr())); } + @Test public void testHasWitnessSignature() { + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + Assert.assertFalse(blockCapsule0.hasWitnessSignature()); blockCapsule0 .sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); @@ -133,4 +146,4 @@ public void testGetTimeStamp() { Assert.assertEquals(1234L, blockCapsule0.getTimeStamp()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java index d1a86f273db..48479287eab 100644 --- a/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java @@ -1,69 +1,22 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.db.StorageMarket; import org.tron.core.exception.ItemNotFoundException; @Slf4j -public class ExchangeCapsuleTest { - - private static final String dbPath = "output_exchange_capsule_test_test"; - private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; - private static final long initBalance = 10_000_000_000_000_000L; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static StorageMarket storageMarket; - private static TronApplicationContext context; +public class ExchangeCapsuleTest extends BaseTest { static { + dbPath = "output_exchange_capsule_test_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - storageMarket = new StorageMarket(chainBaseManager.getAccountStore(), - chainBaseManager.getDynamicPropertiesStore()); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** diff --git a/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java index ed0a3bda670..c9d593daf66 100644 --- a/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java @@ -1,38 +1,26 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Result; import org.tron.protos.Protocol.Transaction.Result.contractResult; @Slf4j -public class TransactionCapsuleTest { +public class TransactionCapsuleTest extends BaseTest { - private static Manager dbManager; - private static TronApplicationContext context; - private static Application AppT; - private static String dbPath = "output_transactioncapsule_test"; private static String OWNER_ADDRESS; - private static String OWNER_KEY = + /*private static String OWNER_KEY = "bfa67cb3dc6609b3a0c98e717d66f38ed1a159b5b3421678dfab85961c40de2f"; private static String TO_ADDRESS; private static String OWNER_ACCOUNT_NOT_Exist; @@ -54,16 +42,14 @@ public class TransactionCapsuleTest { private static String KEY_ADDRESS_23; private static String KEY_ADDRESS_31; private static String KEY_ADDRESS_32; - private static String KEY_ADDRESS_33; + private static String KEY_ADDRESS_33;*/ @BeforeClass public static void init() { + dbPath = "output_transactioncapsule_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "03702350064AD5C1A8AA6B4D74B051199CFF8EA7"; - TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + /*TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ACCOUNT_NOT_Exist = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; KEY_ADDRESS_11 = Wallet.getAddressPreFixString() + "19E7E376E7C213B7E7E7E46CC70A5DD086DAFF2A"; @@ -76,16 +62,7 @@ public static void init() { KEY_ADDRESS_31 = Wallet.getAddressPreFixString() + "77952CE83CA3CAD9F7ADCFABEDA85BD2F1F52008"; KEY_ADDRESS_32 = Wallet.getAddressPreFixString() + "94622CC2A5B64A58C25A129D48A2BEEC4B65B779"; - KEY_ADDRESS_33 = Wallet.getAddressPreFixString() + "5CBDD86A2FA8DC4BDDD8A8F69DBA48572EEC07FB"; - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - AppT.shutdownServices(); - AppT.shutdown(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + KEY_ADDRESS_33 = Wallet.getAddressPreFixString() + "5CBDD86A2FA8DC4BDDD8A8F69DBA48572EEC07FB";*/ } /** @@ -1086,6 +1063,6 @@ public void trxCapsuleClearTest() { Assert.assertEquals(trxCap.getInstance().getRetCount(), 0); trxCap.setResultCode(contractResult); Assert.assertEquals(trxCap.getInstance() - .getRet(0).getContractRet(), contractResult.OUT_OF_TIME); + .getRet(0).getContractRet(), Result.contractResult.OUT_OF_TIME); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java b/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java index b07061dc696..8d56c1a5f21 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java @@ -2,49 +2,30 @@ import com.google.common.collect.Lists; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.BandwidthProcessor; -import org.tron.core.db.Manager; -import org.tron.core.store.AccountAssetStore; import org.tron.protos.Protocol; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class AssetUtilTest { +public class AssetUtilTest extends BaseTest { - private static String dbPath = "output_AssetUtil_test"; - private static Manager dbManager; - private static TronApplicationContext context; - private static ChainBaseManager chainBaseManager; static { + dbPath = "output_AssetUtil_test"; Args.setParam(new String[] {"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } public static byte[] randomBytes(int length) { @@ -54,14 +35,12 @@ public static byte[] randomBytes(int length) { return result; } - private static AccountCapsule createAccount2() { - AccountAssetStore accountAssetStore = dbManager.getAccountAssetStore(); + private AccountCapsule createAccount2() { com.google.protobuf.ByteString accountName = com.google.protobuf.ByteString.copyFrom(randomBytes(16)); com.google.protobuf.ByteString address = ByteString.copyFrom(randomBytes(32)); Protocol.AccountType accountType = Protocol.AccountType.forNumber(1); - AccountCapsule accountCapsule = new AccountCapsule(accountName, address, accountType); - return accountCapsule; + return new AccountCapsule(accountName, address, accountType); } @Test diff --git a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java index 50d01e2b982..3d30dabf031 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java @@ -1,36 +1,22 @@ package org.tron.core.capsule.utils; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; -import org.tron.core.Wallet; import org.tron.core.capsule.ExchangeProcessor; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j -public class ExchangeProcessorTest { +public class ExchangeProcessorTest extends BaseTest { - private static final String dbPath = "output_buy_exchange_processor_test"; - private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; - private static final long initBalance = 10_000_000_000_000_000L; private static ExchangeProcessor processor; - private static TronApplicationContext context; static { + dbPath = "output_buy_exchange_processor_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } /** @@ -40,24 +26,6 @@ public class ExchangeProcessorTest { public static void init() { long supply = 1_000_000_000_000_000_000L; processor = new ExchangeProcessor(supply); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @Test diff --git a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java index 5768fc0b1d8..143e10706aa 100644 --- a/framework/src/test/java/org/tron/core/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/core/config/args/ArgsTest.java @@ -18,6 +18,7 @@ import com.google.common.collect.Lists; import io.grpc.internal.GrpcUtil; import io.grpc.netty.NettyServerBuilder; +import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; @@ -25,11 +26,17 @@ import org.tron.common.args.GenesisBlock; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; @Slf4j public class ArgsTest { + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private String address; + private LocalWitnesses localWitnesses; + @After public void destroy() { Args.clearParam(); @@ -43,6 +50,13 @@ public void get() { Args.logConfig(); + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + address = ByteArray.toHexString(Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine())); + Assert.assertEquals(0, parameter.getBackupPriority()); Assert.assertEquals(3000, parameter.getKeepAliveInterval()); @@ -51,7 +65,7 @@ public void get() { Assert.assertEquals("database", parameter.getStorage().getDbDirectory()); - Assert.assertEquals(11, parameter.getSeedNode().getIpList().size()); + Assert.assertEquals(11, parameter.getSeedNode().getAddressList().size()); GenesisBlock genesisBlock = parameter.getGenesisBlock(); @@ -65,7 +79,7 @@ public void get() { genesisBlock.getParentHash()); Assert.assertEquals( - Lists.newArrayList("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"), + Lists.newArrayList(privateKey), Args.getLocalWitnesses().getPrivateKeys()); Assert.assertTrue(parameter.isNodeDiscoveryEnable()); @@ -91,10 +105,12 @@ public void get() { Assert.assertEquals(GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, parameter.getMaxHeaderListSize()); Assert.assertEquals(1L, parameter.getAllowCreationOfContracts()); - Assert.assertEquals("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62", + Assert.assertEquals(privateKey, Args.getLocalWitnesses().getPrivateKey()); - Assert.assertEquals("a0299f3db80a24b20a254b89ce639d59132f157f13", + + Assert.assertEquals(address, ByteArray.toHexString(Args.getLocalWitnesses() .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()))); } } + diff --git a/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java b/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java new file mode 100644 index 00000000000..2ca95239ad7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java @@ -0,0 +1,71 @@ +package org.tron.core.config.args; + +import java.io.File; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.net.TronNetService; +import org.tron.p2p.P2pConfig; + +public class DynamicArgsTest { + protected TronApplicationContext context; + private DynamicArgs dynamicArgs; + private String dbPath = "output-dynamic-config-test"; + + @Before + public void init() { + Args.setParam(new String[]{"--output-directory", dbPath}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + dynamicArgs = context.getBean(DynamicArgs.class); + + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Test + public void start() { + CommonParameter parameter = Args.getInstance(); + Assert.assertTrue(parameter.isDynamicConfigEnable()); + Assert.assertEquals(600, parameter.getDynamicConfigCheckInterval()); + + dynamicArgs.init(); + Assert.assertEquals(0, (long) ReflectUtils.getFieldObject(dynamicArgs, "lastModified")); + + TronNetService tronNetService = context.getBean(TronNetService.class); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", new P2pConfig()); + File config = new File(Constant.TESTNET_CONF); + if (!config.exists()) { + try { + config.createNewFile(); + } catch (Exception e) { + return; + } + dynamicArgs.run(); + try { + config.delete(); + } catch (Exception e) { + return; + } + } + try { + dynamicArgs.reload(); + } catch (Exception e) { + // no need to deal with + } + + dynamicArgs.close(); + } +} diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index 45466c547d1..d0222254c7d 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -20,17 +20,19 @@ import org.junit.Before; import org.junit.Test; import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; public class LocalWitnessTest { private LocalWitnesses localWitness = new LocalWitnesses(); + private static String PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); @Before public void setLocalWitness() { localWitness .setPrivateKeys( Lists.newArrayList( - "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + PRIVATE_KEY)); } @Test @@ -52,16 +54,16 @@ public void whenSetBadFormatPrivateKey() { public void whenSetPrefixPrivateKey() { localWitness .setPrivateKeys(Lists - .newArrayList("0xf31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + .newArrayList("0x" + PRIVATE_KEY)); localWitness .setPrivateKeys(Lists - .newArrayList("0Xf31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + .newArrayList("0X" + PRIVATE_KEY)); } @Test public void getPrivateKey() { Assert.assertEquals(Lists - .newArrayList("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"), + .newArrayList(PRIVATE_KEY), localWitness.getPrivateKeys()); } } diff --git a/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java index 6e50f3dfca7..fa31b2fd451 100644 --- a/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java @@ -1,23 +1,21 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.AccountIdIndexStore; import org.tron.protos.Protocol.AccountType; -public class AccountIdIndexStoreTest { +public class AccountIdIndexStoreTest extends BaseTest { private static final byte[] ACCOUNT_ADDRESS_ONE = randomBytes(16); private static final byte[] ACCOUNT_ADDRESS_TWO = randomBytes(16); @@ -28,30 +26,21 @@ public class AccountIdIndexStoreTest { private static final byte[] ACCOUNT_NAME_THREE = randomBytes(6); private static final byte[] ACCOUNT_NAME_FOUR = randomBytes(6); private static final byte[] ACCOUNT_NAME_FIVE = randomBytes(6); - private static String dbPath = "output_AccountIndexStore_test"; - private static TronApplicationContext context; - private static AccountIdIndexStore accountIdIndexStore; + @Resource + private AccountIdIndexStore accountIdIndexStore; private static AccountCapsule accountCapsule1; private static AccountCapsule accountCapsule2; private static AccountCapsule accountCapsule3; private static AccountCapsule accountCapsule4; static { + dbPath = "output_AccountIndexStore_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - accountIdIndexStore = context.getBean(AccountIdIndexStore.class); accountCapsule1 = new AccountCapsule(ByteString.copyFrom(ACCOUNT_ADDRESS_ONE), ByteString.copyFrom(ACCOUNT_NAME_ONE), AccountType.Normal); accountCapsule1.setAccountId(ByteString.copyFrom(ACCOUNT_NAME_ONE).toByteArray()); @@ -64,6 +53,11 @@ public static void init() { accountCapsule4 = new AccountCapsule(ByteString.copyFrom(ACCOUNT_ADDRESS_FOUR), ByteString.copyFrom(ACCOUNT_NAME_FOUR), AccountType.Normal); accountCapsule4.setAccountId(ByteString.copyFrom(ACCOUNT_NAME_FOUR).toByteArray()); + + } + + @Before + public void before() { accountIdIndexStore.put(accountCapsule1); accountIdIndexStore.put(accountCapsule2); accountIdIndexStore.put(accountCapsule3); diff --git a/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java index fd0474f4dee..0b449addc41 100755 --- a/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java @@ -1,32 +1,29 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.AccountIndexStore; import org.tron.protos.Protocol.AccountType; -public class AccountIndexStoreTest { +public class AccountIndexStoreTest extends BaseTest { - private static String dbPath = "output_AccountIndexStore_test"; private static String dbDirectory = "db_AccountIndexStore_test"; private static String indexDirectory = "index_AccountIndexStore_test"; - private static TronApplicationContext context; - private static AccountIndexStore accountIndexStore; + @Resource + private AccountIndexStore accountIndexStore; private static byte[] address = TransactionStoreTest.randomBytes(32); private static byte[] accountName = TransactionStoreTest.randomBytes(32); static { + dbPath = "output_AccountIndexStore_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -35,19 +32,10 @@ public class AccountIndexStoreTest { }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); } - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - - @BeforeClass - public static void init() { - accountIndexStore = context.getBean(AccountIndexStore.class); + @Before + public void init() { AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom(address), ByteString.copyFrom(accountName), AccountType.forNumber(1)); diff --git a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java index 44efc7f1e97..f199b371f9d 100755 --- a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java @@ -3,46 +3,40 @@ import static org.junit.Assert.assertEquals; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import java.util.Map; - -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db2.ISession; -import org.tron.core.store.AccountAssetStore; import org.tron.core.store.AccountStore; import org.tron.core.store.AssetIssueStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.AccountType; -public class AccountStoreTest { +public class AccountStoreTest extends BaseTest { private static final byte[] data = TransactionStoreTest.randomBytes(32); - private static String dbPath = "output_AccountStore_test"; private static String dbDirectory = "db_AccountStore_test"; private static String indexDirectory = "index_AccountStore_test"; - private static TronApplicationContext context; - private static AccountStore accountStore; - private static AccountAssetStore accountAssetStore; - private static Manager manager; - private static DynamicPropertiesStore dynamicPropertiesStore; - private static AssetIssueStore assetIssueStore; - private static ChainBaseManager chainBaseManager; + @Resource + private AccountStore accountStore; + @Resource + private DynamicPropertiesStore dynamicPropertiesStore; + @Resource + private AssetIssueStore assetIssueStore; private static byte[] address = TransactionStoreTest.randomBytes(32); private static byte[] accountName = TransactionStoreTest.randomBytes(32); + private static boolean init; static { + dbPath = "output_AccountStore_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -51,23 +45,13 @@ public class AccountStoreTest { }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } - @BeforeClass - public static void init() { - accountStore = context.getBean(AccountStore.class); - accountAssetStore = context.getBean(AccountAssetStore.class); - dynamicPropertiesStore = context.getBean(DynamicPropertiesStore.class); - manager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); + @Before + public void init() { + if (init) { + return; + } assetIssueStore = chainBaseManager.getAssetIssueStore(); dynamicPropertiesStore.saveAllowBlackHoleOptimization(1); AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom(address), @@ -75,6 +59,7 @@ public static void init() { AccountType.forNumber(1)); accountStore.put(data, accountCapsule); + init = true; } @Test @@ -149,7 +134,7 @@ public void assetTest() { assertEquals(100, (long)assets.get("200")); accountCapsule.clearAsset(); - try (ISession tmpSession = manager.getRevokingStore().buildSession()) { + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { accountCapsule.addAssetAmountV2("100".getBytes(), 1, dynamicPropertiesStore, assetIssueStore); accountCapsule.reduceAssetAmountV2("200".getBytes(), 1, @@ -160,11 +145,11 @@ public void assetTest() { assertEquals(101, accountCapsule.getAssetV2("100")); assertEquals(99, accountCapsule.getAssetV2("200")); - try (ISession tmpSession = manager.getRevokingStore().buildSession()) { + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { tmpSession.commit(); } - try (ISession tmpSession = manager.getRevokingStore().buildSession()) { + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { accountCapsule.reduceAssetAmountV2("200".getBytes(), 89, dynamicPropertiesStore, assetIssueStore); accountCapsule.addAssetAmountV2("300".getBytes(), 10, @@ -178,7 +163,7 @@ public void assetTest() { assertEquals(10, (long)assets.get("200")); assertEquals(10, (long)assets.get("300")); - try (ISession tmpSession = manager.getRevokingStore().buildSession()) { + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { accountCapsule.reduceAssetAmountV2("100".getBytes(), 91, dynamicPropertiesStore, assetIssueStore); accountCapsule.addAssetAmountV2("200".getBytes(), 0, diff --git a/framework/src/test/java/org/tron/core/db/BlockGenerate.java b/framework/src/test/java/org/tron/core/db/BlockGenerate.java index d7a2d21e408..197dd562485 100644 --- a/framework/src/test/java/org/tron/core/db/BlockGenerate.java +++ b/framework/src/test/java/org/tron/core/db/BlockGenerate.java @@ -1,6 +1,7 @@ package org.tron.core.db; import com.google.protobuf.ByteString; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.parameter.CommonParameter; diff --git a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java index 0a5df8bf9bd..cdf8dbcc29c 100644 --- a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java @@ -1,40 +1,19 @@ package org.tron.core.db; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j -public class BlockStoreTest { +public class BlockStoreTest extends BaseTest { - private static final String dbPath = "output-blockStore-test"; - private static TronApplicationContext context; static { + dbPath = "output-blockStore-test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - BlockStore blockStore; - - @Before - public void init() { - blockStore = context.getBean(BlockStore.class); - } - - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java new file mode 100644 index 00000000000..ef4a60ca1da --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java @@ -0,0 +1,22 @@ +package org.tron.core.db; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.testng.Assert; +import org.tron.common.utils.ByteArray; + +@Slf4j +public class ByteArrayWrapperTest { + + @Test + public void createByteArray() { + ByteArrayWrapper byteArrayWrapper1 = new ByteArrayWrapper(ByteArray.fromHexString("1")); + ByteArrayWrapper byteArrayWrapper2 = new ByteArrayWrapper(ByteArray.fromHexString("2")); + Assert.assertEquals(byteArrayWrapper1.compareTo(byteArrayWrapper2), -1); + Assert.assertFalse(byteArrayWrapper1.equals(byteArrayWrapper2)); + Assert.assertFalse(byteArrayWrapper1.getData().equals(byteArrayWrapper2.getData())); + Assert.assertTrue(byteArrayWrapper1.hashCode() != byteArrayWrapper2.hashCode()); + Assert.assertEquals(byteArrayWrapper1.toString().equals(byteArrayWrapper2.toString()),false); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java b/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java index 13107480bf5..ca115bed2bd 100644 --- a/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java +++ b/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java @@ -8,20 +8,14 @@ import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE; import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK; -import java.io.File; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.api.EnergyPriceHistoryLoader; import org.tron.core.store.ProposalStore; @@ -30,11 +24,8 @@ @Slf4j -public class EnergyPriceHistoryLoaderTest { +public class EnergyPriceHistoryLoaderTest extends BaseTest { - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static String dbPath = "output-EnergyPriceHistoryLoaderTest-test"; private static long t1 = 1542607200000L; private static long price1 = 20; private static long t3 = 1544724000000L; @@ -45,24 +36,8 @@ public class EnergyPriceHistoryLoaderTest { private static long price5 = 140L; static { + dbPath = "output-EnergyPriceHistoryLoaderTest-test"; Args.setParam(new String[] {"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } public void initDB() { @@ -102,7 +77,7 @@ public void initDB() { initProposal(parameters, 1572609600000L, State.CANCELED); } - private static void initProposal(long code, long timestamp, long price, State state) { + private void initProposal(long code, long timestamp, long price, State state) { long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; Proposal proposal = Proposal.newBuilder().putParameters(code, price) @@ -116,7 +91,7 @@ private static void initProposal(long code, long timestamp, long price, State st chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(id); } - private static void initProposal(Map parameters, long timestamp, State state) { + private void initProposal(Map parameters, long timestamp, State state) { long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; Proposal proposal = Proposal.newBuilder().putAllParameters(parameters) @@ -132,9 +107,6 @@ private static void initProposal(Map parameters, long timestamp, Sta @Test public void testLoader() { - if (chainBaseManager == null) { - init(); - } EnergyPriceHistoryLoader loader = new EnergyPriceHistoryLoader(chainBaseManager); initDB(); @@ -154,10 +126,6 @@ public void testLoader() { @Test public void testProposalEmpty() { - if (chainBaseManager == null) { - init(); - } - // clean DB firstly ProposalStore proposalStore = chainBaseManager.getProposalStore(); proposalStore.forEach( diff --git a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java index 031bb47eba2..87a38927be1 100644 --- a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java +++ b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java @@ -1,25 +1,22 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Pair; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadNumberBlockException; import org.tron.core.exception.NonCommonBlockException; @@ -29,28 +26,19 @@ import org.tron.protos.Protocol.BlockHeader.raw; @Slf4j -public class KhaosDatabaseTest { +public class KhaosDatabaseTest extends BaseTest { - private static final String dbPath = "output-khaosDatabase-test"; - private static KhaosDatabase khaosDatabase; - private static TronApplicationContext context; + @Resource + private KhaosDatabase khaosDatabase; static { + dbPath = "output-khaosDatabase-test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } @BeforeClass public static void init() { Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - khaosDatabase = context.getBean(KhaosDatabase.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/db/ManagerTest.java b/framework/src/test/java/org/tron/core/db/ManagerTest.java index e7319d0ed0b..2c51250d757 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -4,13 +4,16 @@ import static org.tron.common.utils.Commons.adjustBalance; import static org.tron.common.utils.Commons.adjustTotalShieldedPoolValue; import static org.tron.common.utils.Commons.getExchangeStoreFinal; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; import com.google.common.collect.Maps; import com.google.protobuf.ByteString; import java.io.File; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -19,11 +22,16 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.testng.collections.Sets; import org.tron.common.application.TronApplicationContext; import org.tron.common.crypto.ECKey; +import org.tron.common.runtime.RuntimeImpl; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; import org.tron.common.utils.JsonUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; @@ -37,8 +45,12 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.WitnessCapsule; import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.accountstate.AccountStateEntity; +import org.tron.core.db.accountstate.TrieService; +import org.tron.core.db.accountstate.storetrie.AccountStateStoreTrie; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadBlockException; import org.tron.core.exception.BadItemException; @@ -66,6 +78,8 @@ import org.tron.core.store.ExchangeStore; import org.tron.core.store.ExchangeV2Store; import org.tron.core.store.IncrementalMerkleTreeStore; +import org.tron.core.store.StoreFactory; +import org.tron.protos.Protocol; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; @@ -90,6 +104,8 @@ public class ManagerTest extends BlockGenerate { private static AtomicInteger port = new AtomicInteger(0); private static String accountAddress = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private LocalWitnesses localWitnesses; @Before public void init() { @@ -103,6 +119,12 @@ public void init() { consensusService = context.getBean(ConsensusService.class); consensusService.start(); chainManager = dbManager.getChainBaseManager(); + + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + blockCapsule2 = new BlockCapsule( 1, @@ -119,6 +141,16 @@ public void init() { blockCapsule2.sign( ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); Assert.assertTrue(dbManager.getMaxFlushCount() == 200); + + byte[] address = PublicMethod.getAddressByteByPrivateKey(privateKey); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); } @After @@ -141,6 +173,17 @@ public void updateRecentTransaction() throws Exception { 0, ByteString.copyFrom(new byte[64])); b.addTransaction(trx); dbManager.updateRecentTransaction(b); + try { + dbManager.consumeBandwidth(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + } + dbManager.consumeMemoFee(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + Assert.assertTrue(dbManager.getTxListFromPending().isEmpty()); + Assert.assertNull(dbManager.getTxFromPending(trx.getTransactionId().toString())); + Assert.assertEquals(0, dbManager.getPendingSize()); Assert.assertEquals(1, chainManager.getRecentTransactionStore().size()); byte[] key = ByteArray.subArray(ByteArray.fromLong(1), 6, 8); byte[] value = chainManager.getRecentTransactionStore().get(key).getData(); @@ -180,6 +223,7 @@ public void setBlockReference() .setToAddress(ByteString.copyFromUtf8("bbb")) .build(); TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); + if (chainManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 0) { dbManager.pushBlock(blockCapsule); Assert.assertEquals(1, @@ -211,6 +255,9 @@ public void pushBlock() { } catch (Exception e) { Assert.assertTrue("pushBlock is error", false); } + TrieService trieService = context.getBean(TrieService.class); + Assert.assertTrue(trieService.getFullAccountStateRootHash().length > 0); + Assert.assertTrue(trieService.getSolidityAccountStateRootHash().length > 0); if (isUnlinked) { Assert.assertEquals("getBlockIdByNum is error", @@ -226,9 +273,56 @@ public void pushBlock() { } } + try { + chainManager.getBlockIdByNum(-1); + Assert.fail(); + } catch (ItemNotFoundException e) { + Assert.assertTrue(true); + } + try { + dbManager.getBlockChainHashesOnFork(blockCapsule2.getBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof NonCommonBlockException); + } Assert.assertTrue("hasBlocks is error", chainManager.hasBlocks()); } + @Test + public void transactionTest() { + TransactionCapsule trans0 = new TransactionCapsule(Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder().setData(ByteString.copyFrom( + new byte[Parameter.ChainConstant.BLOCK_SIZE + Constant.ONE_THOUSAND]))).build(), + ContractType.ShieldedTransferContract); + ShieldContract.ShieldedTransferContract trx1 = ShieldContract.ShieldedTransferContract + .newBuilder() + .setFromAmount(10) + .setToAmount(10) + .build(); + TransactionCapsule trans = new TransactionCapsule(trx1, ContractType.ShieldedTransferContract); + try { + dbManager.pushTransaction(trans0); + dbManager.pushTransaction(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + dbManager.rePush(trans0); + ReflectUtils.invokeMethod(dbManager,"filterOwnerAddress", + new Class[]{trans.getClass(), Set.class},trans, Sets.newHashSet()); + Assert.assertNotNull(dbManager.getTxListFromPending()); + + try { + dbManager.validateTapos(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + try { + dbManager.pushVerifiedBlock(chainManager.getHead()); + dbManager.getBlockChainHashesOnFork(chainManager.getHeadBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + } + @Test public void GetterInstanceTest() { @@ -252,6 +346,24 @@ public void GetterInstanceTest() { } + @Test + public void entityTest() { + AccountStateStoreTrie trie = context.getBean(AccountStateStoreTrie.class); + Assert.assertNull(trie.getAccount("".getBytes())); + Assert.assertNull(trie.getAccount("".getBytes(), "".getBytes())); + Assert.assertNull(trie.getSolidityAccount("".getBytes())); + Assert.assertTrue(trie.isEmpty()); + AccountStateEntity entity = new AccountStateEntity(); + AccountStateEntity parsedEntity = AccountStateEntity.parse("".getBytes()); + Assert.assertTrue(parsedEntity != null); + Assert.assertTrue(parsedEntity.getAccount() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Account.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.AssetIssue.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Block.of() != null); + Assert.assertTrue(org.tron.core.db.api.pojo.Transaction.of() != null); + + } + @Test public void getHeadTest() { try { @@ -392,6 +504,7 @@ public void pushBlockInvalidMerkelRoot() { Assert.assertTrue(false); } catch (BadBlockException e) { Assert.assertTrue(e instanceof BadBlockException); + Assert.assertTrue(e.getType().equals(CALC_MERKLE_ROOT_FAILED)); Assert.assertEquals("The merkle hash is not validated for " + blockCapsule2.getNum(), e.getMessage()); } catch (Exception e) { @@ -931,4 +1044,25 @@ private BlockCapsule createTestBlockCapsuleError(long time, blockCapsule.sign(ByteArray.fromHexString(addressToProvateKeys.get(witnessAddress))); return blockCapsule; } + + @Test + public void testExpireTransaction() { + TransferContract tc = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); + long latestBlockTime = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + trx.setExpiration(latestBlockTime - 100); + try { + dbManager.validateCommon(trx); + Assert.fail(); + } catch (TransactionExpirationException e) { + Assert.assertTrue(true); + } catch (TooBigTransactionException e) { + Assert.fail(); + } + } } diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index a264b33ee98..f90b5712c56 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -1,22 +1,17 @@ package org.tron.core.db; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.ItemNotFoundException; import org.tron.core.store.MarketPairPriceToOrderStore; @@ -25,34 +20,11 @@ import org.tron.protos.Protocol.MarketPrice; @Slf4j -public class MarketPairPriceToOrderStoreTest { - - private static final String dbPath = "output-MarketPairPriceToOrderStore-test"; - private static TronApplicationContext context; - private static Manager dbManager; +public class MarketPairPriceToOrderStoreTest extends BaseTest { static { + dbPath = "output-MarketPairPriceToOrderStore-test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @After diff --git a/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java b/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java index 58de5f0747f..5ed2f967a15 100644 --- a/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java @@ -1,57 +1,48 @@ package org.tron.core.db; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; 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.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.NullifierStore; -public class NullifierStoreTest { +public class NullifierStoreTest extends BaseTest { private static final byte[] NULLIFIER_ONE = randomBytes(32); private static final byte[] NULLIFIER_TWO = randomBytes(32); private static final byte[] TRX_TWO = randomBytes(32); private static final byte[] TRX_TWO_NEW = randomBytes(32); - public static Application AppT; - private static NullifierStore nullifierStore; - private static String dbPath = "output_NullifierStore_test"; - private static TronApplicationContext context; + @Resource + public Application AppT; + @Resource + private NullifierStore nullifierStore; private static BytesCapsule nullifier1; private static BytesCapsule nullifier2; private static BytesCapsule nullifier2New; static { + dbPath = "output_NullifierStore_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - nullifierStore = context.getBean(NullifierStore.class); nullifier1 = new BytesCapsule(NULLIFIER_ONE); nullifier2 = new BytesCapsule(TRX_TWO); nullifier2New = new BytesCapsule(TRX_TWO_NEW); + } + @Before + public void before() { nullifierStore.put(nullifier1); nullifierStore.put(NULLIFIER_TWO, nullifier2); } diff --git a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java new file mode 100644 index 00000000000..f9b1a6c44e0 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java @@ -0,0 +1,108 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.lang.reflect.Array; +import java.util.Arrays; + +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.GrpcAPI.Return.response_code; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Sha256Hash; +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.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.store.WitnessScheduleStore; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.BalanceContract.TransferContract; + +@Slf4j +public class TransactionExpireTest { + + private String dbPath = "output_expire_test"; + private TronApplicationContext context; + private Wallet wallet; + private Manager dbManager; + private BlockCapsule blockCapsule; + + @Before + public void init() { + Args.setParam(new String[] {"--output-directory", dbPath}, Constant.TEST_CONF); + CommonParameter.PARAMETER.setMinEffectiveConnection(0); + + context = new TronApplicationContext(DefaultConfig.class); + wallet = context.getBean(Wallet.class); + dbManager = context.getBean(Manager.class); + + blockCapsule = new BlockCapsule( + 1, + Sha256Hash.wrap(ByteString.copyFrom( + ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), + 1, + ByteString.copyFromUtf8("testAddress")); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(blockCapsule.getNum()); + dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(blockCapsule.getTimeStamp()); + dbManager.updateRecentBlock(blockCapsule); + initLocalWitness(); + } + + private void initLocalWitness() { + String randomPrivateKey = PublicMethod.getRandomPrivateKey(); + LocalWitnesses localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(randomPrivateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + if (FileUtil.deleteDir(new File(dbPath))) { + logger.info("Release resources successful."); + } else { + logger.info("Release resources failure."); + } + } + + @Test + public void testExpireTransaction() { + TransferContract transferContract = TransferContract.newBuilder() + .setAmount(1L) + .setOwnerAddress(ByteString.copyFrom(Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) + .build(); + TransactionCapsule transactionCapsule = + new TransactionCapsule(transferContract, ContractType.TransferContract); + transactionCapsule.setReference(blockCapsule.getNum(), blockCapsule.getBlockId().getBytes()); + Assert.assertEquals(1, blockCapsule.getTimeStamp()); + + long blockTimeStamp = blockCapsule.getTimeStamp(); + transactionCapsule.setExpiration(blockTimeStamp - 1); + transactionCapsule.sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); + + GrpcAPI.Return result = wallet.broadcastTransaction(transactionCapsule.getInstance()); + Assert.assertEquals(response_code.TRANSACTION_EXPIRATION_ERROR, result.getCode()); + } +} diff --git a/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java b/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java index c7439d84d82..812f19922ca 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java @@ -1,30 +1,30 @@ package org.tron.core.db; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionInfoCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.store.TransactionHistoryStore; -public class TransactionHistoryTest { +public class TransactionHistoryTest extends BaseTest { private static final byte[] transactionId = TransactionStoreTest.randomBytes(32); - private static String dbPath = "output_TransactionHistoryStore_test"; private static String dbDirectory = "db_TransactionHistoryStore_test"; private static String indexDirectory = "index_TransactionHistoryStore_test"; - private static TronApplicationContext context; - private static TransactionHistoryStore transactionHistoryStore; + @Resource + private TransactionHistoryStore transactionHistoryStore; + + private static TransactionInfoCapsule transactionInfoCapsule; static { + dbPath = "output_TransactionHistoryStore_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -33,25 +33,20 @@ public class TransactionHistoryTest { }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - transactionHistoryStore = context.getBean(TransactionHistoryStore.class); - TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); - + transactionInfoCapsule = new TransactionInfoCapsule(); transactionInfoCapsule.setId(transactionId); transactionInfoCapsule.setFee(1000L); transactionInfoCapsule.setBlockNumber(100L); transactionInfoCapsule.setBlockTimeStamp(200L); + + } + + @Before + public void before() { transactionHistoryStore.put(transactionId, transactionInfoCapsule); } diff --git a/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java b/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java index c4a629b12bc..04478f2c261 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java @@ -1,52 +1,44 @@ package org.tron.core.db; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; import org.tron.core.capsule.TransactionRetCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.store.TransactionRetStore; import org.tron.protos.Protocol.Transaction; -public class TransactionRetStoreTest { +public class TransactionRetStoreTest extends BaseTest { private static final byte[] transactionId = TransactionStoreTest.randomBytes(32); private static final byte[] blockNum = ByteArray.fromLong(1); - private static String dbPath = "output_TransactionRetStore_test"; private static String dbDirectory = "db_TransactionRetStore_test"; private static String indexDirectory = "index_TransactionRetStore_test"; - private static TronApplicationContext context; - private static TransactionRetStore transactionRetStore; + @Resource + private TransactionRetStore transactionRetStore; private static Transaction transaction; - private static TransactionStore transactionStore; + @Resource + private TransactionStore transactionStore; + + private static TransactionCapsule transactionCapsule; + private static TransactionRetCapsule transactionRetCapsule; static { + dbPath = "output_TransactionRetStore_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - transactionRetStore = context.getBean(TransactionRetStore.class); - transactionStore = context.getBean(TransactionStore.class); TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); transactionInfoCapsule.setId(transactionId); @@ -54,12 +46,18 @@ public static void init() { transactionInfoCapsule.setBlockNumber(100L); transactionInfoCapsule.setBlockTimeStamp(200L); - TransactionRetCapsule transactionRetCapsule = new TransactionRetCapsule(); + transactionRetCapsule = new TransactionRetCapsule(); transactionRetCapsule.addTransactionInfo(transactionInfoCapsule.getInstance()); - transactionRetStore.put(blockNum, transactionRetCapsule); + transaction = Transaction.newBuilder().build(); - TransactionCapsule transactionCapsule = new TransactionCapsule(transaction); + transactionCapsule = new TransactionCapsule(transaction); transactionCapsule.setBlockNum(1); + + } + + @Before + public void before() { + transactionRetStore.put(blockNum, transactionRetCapsule); transactionStore.put(transactionId, transactionCapsule); } diff --git a/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java b/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java index 7993ee5b19c..f51a8744c74 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java @@ -1,26 +1,21 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; -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.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; @@ -32,7 +27,7 @@ import org.tron.protos.contract.WitnessContract.VoteWitnessContract.Vote; import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -public class TransactionStoreTest { +public class TransactionStoreTest extends BaseTest { private static final byte[] key1 = TransactionStoreTest.randomBytes(21); private static final byte[] key2 = TransactionStoreTest.randomBytes(21); @@ -45,35 +40,19 @@ public class TransactionStoreTest { private static final long AMOUNT = 100; private static final String WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - private static String dbPath = "output_TransactionStore_test"; private static String dbDirectory = "db_TransactionStore_test"; private static String indexDirectory = "index_TransactionStore_test"; - private static TransactionStore transactionStore; - private static TronApplicationContext context; - private static Application AppT; - private static ChainBaseManager chainBaseManager; + @Resource + private TransactionStore transactionStore; /** * Init data. */ @BeforeClass public static void init() { + dbPath = "output_TransactionStore_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - chainBaseManager = context.getBean(ChainBaseManager.class); - transactionStore = chainBaseManager.getTransactionStore(); - } - - /** - * release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } /** @@ -204,8 +183,7 @@ public void createAccountTransactionStoreTest() throws BadItemException { public void getUncheckedTransactionTest() { final BlockStore blockStore = chainBaseManager.getBlockStore(); final TransactionStore trxStore = chainBaseManager.getTransactionStore(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - + String key = PublicMethod.getRandomPrivateKey(); BlockCapsule blockCapsule = new BlockCapsule( 1, diff --git a/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java b/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java index cb47bce4df6..553eb46a725 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java @@ -18,22 +18,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -53,58 +48,19 @@ import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -public class TransactionTraceTest { +public class TransactionTraceTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_TransactionTrace_test"; private static String dbDirectory = "db_TransactionTrace_test"; private static String indexDirectory = "index_TransactionTrace_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; private static ByteString ownerAddress = ByteString.copyFrom(ByteArray.fromInt(1)); private static ByteString contractAddress = ByteString.copyFrom(ByteArray.fromInt(2)); - - /* - * DeployContract tracetestContract [{"constant":false,"inputs":[{"name":"accountId","type": - * "uint256"}],"name":"getVoters","outputs":[{"name":"","type":"uint256"}],"payable":false," - * stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type" - * :"uint256"}],"name":"voters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"vote","type" - * :"uint256"}],"name":"addVoters","outputs":[],"payable":false,"stateMutability":"nonpayable", - * "type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type": - * "constructor"}] 608060405234801561001057600080fd5b5060015b620186a081101561003857600081815260 - * 2081905260409020819055600a01610014565b5061010b806100486000396000f300608060405260043610605257 - * 63ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166386b646f281 - * 146057578063da58c7d914607e578063eb91a5ff146093575b600080fd5b348015606257600080fd5b50606c6004 - * 3560aa565b60408051918252519081900360200190f35b348015608957600080fd5b50606c60043560bc565b3480 - * 15609e57600080fd5b5060a860043560ce565b005b60009081526020819052604090205490565b60006020819052 - * 908152604090205481565b6000818152602081905260409020555600a165627a7a72305820f9935f89890e51bcf3 - * ea98fa4841c91ac5957a197d99eeb7879a775b30ee9a2d0029 1000000000 100 - * */ - /* - * DeployContract tracetestContract [{"constant":false,"inputs":[{"name":"accountId","type": - * "uint256"}],"name":"getVoters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"", - * "type":"uint256"}],"name":"voters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"vote","type" - * :"uint256"}],"name":"addVoters","outputs":[],"payable":false,"stateMutability":"nonpayable", - * "type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type": - * "constructor"}] 608060405234801561001057600080fd5b5060015b620186a08110156100385760008181526020 - * 81905260409020819055600a01610014565b5061010b806100486000396000f30060806040526004361060525763ff - * ffffff7c010000000000000000000000000000000000000000000000000000000060003504166386b646f281146057 - * 578063da58c7d914607e578063eb91a5ff146093575b600080fd5b348015606257600080fd5b50606c60043560aa56 - * 5b60408051918252519081900360200190f35b348015608957600080fd5b50606c60043560bc565b348015609e576 - * 00080fd5b5060a860043560ce565b005b60009081526020819052604090205490565b6000602081905290815260409 - * 0205481565b6000818152602081905260409020555600a165627a7a72305820f9935f89890e51bcf3ea98fa4841c91 - * ac5957a197d99eeb7879a775b30ee9a2d0029 1000000000 40 - * */ private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - /* - * triggercontract TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj addVoters(uint256) 113 false 1000000000 0 - * */ + private static boolean init; static { + dbPath = "output_TransactionTrace_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -115,31 +71,22 @@ public class TransactionTraceTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); VMConfig.initVmHardFork(false); - - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -436,4 +383,69 @@ public void testPay() throws BalanceInsufficientException { transactionTrace.pay(); AccountCapsule accountCapsule1 = dbManager.getAccountStore().get(ownerAddress.toByteArray()); } + + + @Test + public void testTriggerUseUsageInWindowSizeV2() throws VMIllegalException, ContractExeException, + ContractValidateException, BalanceInsufficientException { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + String contractName = "tracetestContract"; + String code = "608060405234801561001057600080fd5b5060005b6103e88110156100375760008181526020819" + + "05260409020819055600a01610014565b5061010f806100476000396000f300608060405260043610605257" + + "63ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634903b" + + "0d181146057578063da31158814607e578063fe4ba936146093575b600080fd5b348015606257600080fd5b" + + "50606c60043560ad565b60408051918252519081900360200190f35b348015608957600080fd5b50606c600" + + "43560bf565b348015609e57600080fd5b5060ab60043560243560d1565b005b600060208190529081526040" + + "90205481565b60009081526020819052604090205490565b600091825260208290526040909120555600a16" + + "5627a7a723058200596e6c0a5371c2c533eb97ba4c1c19b0521750a5624cb5d2e93249c8b7219d20029"; + String abi = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":" + + "\"balances\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"st" + + "ateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name" + + "\":\"account\",\"type\":\"uint256\"}],\"name\":\"getCoin\",\"outputs\":[{\"name\":\"\"" + + ",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"func" + + "tion\"},{\"constant\":false,\"inputs\":[{\"name\":\"receiver\",\"type\":\"uint256\"},{" + + "\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"setCoin\",\"outputs\":[],\"payab" + + "le\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"" + + "payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]"; + CreateSmartContract smartContract = TvmTestUtils.createSmartContract( + Commons.decodeFromBase58Check(OwnerAddress), contractName, abi, code, 0, + 100); + Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder().addContract( + Contract.newBuilder().setParameter(Any.pack(smartContract)) + .setType(ContractType.CreateSmartContract)).setFeeLimit(1000000000) + .setTimestamp(System.currentTimeMillis())) + .build(); + + byte[] contractAddress = deployInit(transaction); + AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom("owner".getBytes()), + ByteString.copyFrom(Commons.decodeFromBase58Check(TriggerOwnerAddress)), + AccountType.Normal, + totalBalance); + + accountCapsule.setFrozenForEnergy(10_000_000L, 0L); + dbManager.getAccountStore() + .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule); + TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, + "setCoin(uint256,uint256)", "133,133", false, + 0, Commons.decodeFromBase58Check(TriggerOwnerAddress)); + Transaction transaction2 = Transaction.newBuilder().setRawData(raw.newBuilder().addContract( + Contract.newBuilder().setParameter(Any.pack(triggerContract)) + .setType(ContractType.TriggerSmartContract)).setFeeLimit(1000000000L)).build(); + TransactionCapsule transactionCapsule = new TransactionCapsule(transaction2); + TransactionTrace trace = new TransactionTrace(transactionCapsule, StoreFactory + .getInstance(), new RuntimeImpl()); + trace.init(null); + trace.exec(); + trace.pay(); + Assert.assertEquals(0, trace.getReceipt().getEnergyUsage()); + Assert.assertEquals(2025200, trace.getReceipt().getEnergyFee()); + accountCapsule = dbManager.getAccountStore().get(accountCapsule.getAddress().toByteArray()); + Assert.assertEquals(totalBalance, + accountCapsule.getBalance() + trace.getReceipt().getEnergyFee()); + + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + } } diff --git a/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java b/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java index 7d9bbcd5ad2..8b1724248a0 100644 --- a/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java +++ b/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java @@ -1,26 +1,20 @@ package org.tron.core.db; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import org.tron.common.BaseTest; import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.keystore.Wallet; -public class TxCacheDBTest { - private static final String dbPath = "output_TransactionCache_test"; - - private static TronApplicationContext context; - private static Manager dbManager; +public class TxCacheDBTest extends BaseTest { + @Resource + private Application appT; /** * Init data. @@ -29,21 +23,9 @@ public class TxCacheDBTest { public static void init() { String dbDirectory = "db_TransactionCache_test"; String indexDirectory = "index_TransactionCache_test"; + dbPath = "output_TransactionCache_test"; Args.setParam(new String[]{"--output-directory", dbPath, "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - Application appT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); - } - - /** - * release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/db/VotesStoreTest.java b/framework/src/test/java/org/tron/core/db/VotesStoreTest.java index 55b0a4882e3..9e5cd7c0098 100755 --- a/framework/src/test/java/org/tron/core/db/VotesStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/VotesStoreTest.java @@ -1,47 +1,30 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.VotesStore; import org.tron.protos.Protocol.Vote; @Slf4j -public class VotesStoreTest { +public class VotesStoreTest extends BaseTest { - private static final String dbPath = "output-votesStore-test"; - private static TronApplicationContext context; static { + dbPath = "output-votesStore-test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } - VotesStore votesStore; - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - - @Before - public void initDb() { - this.votesStore = context.getBean(VotesStore.class); - } + @Resource + private VotesStore votesStore; @Test public void putAndGetVotes() { diff --git a/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java b/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java index 5ae37650b6a..fd91e7da72a 100755 --- a/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java @@ -1,44 +1,26 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.WitnessStore; @Slf4j -public class WitnessStoreTest { - - private static final String dbPath = "output-witnessStore-test"; - private static TronApplicationContext context; +public class WitnessStoreTest extends BaseTest { static { + dbPath = "output-witnessStore-test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } - WitnessStore witnessStore; - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - - @Before - public void initDb() { - this.witnessStore = context.getBean(WitnessStore.class); - } + @Resource + private WitnessStore witnessStore; @Test public void putAndGetWitness() { diff --git a/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java b/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java index 34ce5d7d6ec..714198bde51 100644 --- a/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java +++ b/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java @@ -3,51 +3,40 @@ import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; +import java.util.Objects; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; -import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Exchange; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -public class AssetUpdateHelperTest { +public class AssetUpdateHelperTest extends BaseTest { - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static String dbPath = "output_AssetUpdateHelperTest_test"; - private static Application AppT; - - private static ByteString assetName = ByteString.copyFrom("assetIssueName".getBytes()); + private static final ByteString assetName = ByteString.copyFrom("assetIssueName".getBytes()); + private static boolean init; static { + dbPath = "output_AssetUpdateHelperTest_test"; Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-test-index.conf"); Args.getInstance().setSolidityNode(true); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); } - @BeforeClass - public static void init() { - - chainBaseManager = context.getBean(ChainBaseManager.class); - + @Before + public void init() { + if (init) { + return; + } AssetIssueContract contract = AssetIssueContract.newBuilder().setName(assetName).setNum(12581).setPrecision(5).build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(contract); @@ -84,13 +73,7 @@ public static void init() { .build()); chainBaseManager.getAccountStore().put(ByteArray.fromHexString("121212abc"), accountCapsule); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -112,7 +95,7 @@ public void test() { Assert.assertEquals(5L, assetIssueCapsule.getPrecision()); AssetIssueCapsule assetIssueCapsule2 = - chainBaseManager.getAssetIssueV2Store().get(ByteArray.fromString(String.valueOf(idNum))); + chainBaseManager.getAssetIssueV2Store().get(ByteArray.fromString(idNum)); Assert.assertEquals(idNum, assetIssueCapsule2.getId()); Assert.assertEquals(assetName, assetIssueCapsule2.getName()); @@ -139,7 +122,8 @@ public void test() { chainBaseManager.getAccountStore().get(ByteArray.fromHexString("121212abc")); Assert.assertEquals( - ByteString.copyFrom(ByteArray.fromString("1000001")), accountCapsule.getAssetIssuedID()); + ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString("1000001"))), + accountCapsule.getAssetIssuedID()); Assert.assertEquals(1, accountCapsule.getAssetV2MapForTest().size()); diff --git a/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java b/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java index f63fafe060e..4ddbd88d338 100644 --- a/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java +++ b/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java @@ -1,51 +1,41 @@ package org.tron.core.db.backup; import java.io.File; -import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.rocksdb.RocksDB; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; import org.tron.consensus.dpos.DposSlot; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.Manager; import org.tron.core.db.ManagerForTest; -import org.tron.core.db2.core.Chainbase; -import org.tron.core.db2.core.SnapshotManager; @Slf4j -public class BackupDbUtilTest { +public class BackupDbUtilTest extends BaseTest { static { RocksDB.loadLibrary(); } - public TronApplicationContext context; - public Application AppT = null; - public BackupDbUtil dbBackupUtil; - public Manager dbManager; + @Resource public ConsensusService consensusService; + @Resource public DposSlot dposSlot; public ManagerForTest mngForTest; - public String dbPath = "output-BackupDbUtilTest"; String propPath; String bak1Path; String bak2Path; int frequency; - @Before - public void before() { + static { + dbPath = "output-BackupDbUtilTest"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -54,16 +44,12 @@ public void before() { }, "config-test-dbbackup.conf" ); + } - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); - dposSlot = context.getBean(DposSlot.class); - consensusService = context.getBean(ConsensusService.class); - dbBackupUtil = context.getBean(BackupDbUtil.class); + @Before + public void before() { consensusService.start(); mngForTest = new ManagerForTest(dbManager, dposSlot); - //prepare prop.properties propPath = dbPath + File.separator + "test_prop.properties"; bak1Path = dbPath + File.separator + "bak1/database"; @@ -75,49 +61,30 @@ public void before() { FileUtil.createFileIfNotExists(propPath); } - @After - public void after() { - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testDoBackup() { - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("11")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "11"); mngForTest.pushNTestBlock(50); - List alist = ((SnapshotManager) dbBackupUtil.getDb()).getDbs(); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 50); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(50, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 100); - Assert.assertTrue("11".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(100, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("11", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 150); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(150, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("1")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "1"); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 200); - Assert.assertTrue("11".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(200, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("11", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("2")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "2"); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 250); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(250, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); } } diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java index f7985017285..a483be278ff 100644 --- a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java +++ b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -11,9 +13,12 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.util.CollectionUtils; +import org.testng.collections.Sets; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; +import org.tron.common.cache.CacheStrategies; import org.tron.common.utils.FileUtil; import org.tron.common.utils.SessionOptional; import org.tron.core.Constant; @@ -24,6 +29,7 @@ import org.tron.core.db2.core.Snapshot; import org.tron.core.db2.core.SnapshotManager; import org.tron.core.db2.core.SnapshotRoot; +import org.tron.core.exception.ItemNotFoundException; public class SnapshotRootTest { @@ -31,6 +37,15 @@ public class SnapshotRootTest { private TronApplicationContext context; private Application appT; private SnapshotManager revokingDatabase; + private final Set noSecondCacheDBs = Sets.newHashSet(Arrays.asList("trans-cache", + "exchange-v2","nullifier","accountTrie","transactionRetStore","accountid-index", + "market_account","market_pair_to_price","recent-transaction","block-index","block", + "market_pair_price_to_order","proposal","tree-block-index","IncrementalMerkleTree", + "asset-issue","balance-trace","transactionHistoryStore","account-index","section-bloom", + "exchange","market_order","account-trace","contract-state","trans")); + private Set allDBNames; + private Set allRevokingDBNames; + @Before public void init() { @@ -113,6 +128,52 @@ public synchronized void testMergeList() { tronDatabase.close(); } + @Test + public void testSecondCacheCheck() + throws ItemNotFoundException { + revokingDatabase = context.getBean(SnapshotManager.class); + allRevokingDBNames = parseRevokingDBNames(context); + allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list()) + .collect(Collectors.toSet()); + if (CollectionUtils.isEmpty(allDBNames)) { + throw new ItemNotFoundException("No DBs found"); + } + allDBNames.removeAll(noSecondCacheDBs); + allDBNames.removeAll(CacheStrategies.CACHE_DBS); + allDBNames.retainAll(allRevokingDBNames); + org.junit.Assert.assertEquals(String.format("New added dbs %s " + + "shall consider to add second cache or add to noNeedCheckDBs!", + allDBNames.stream().collect(Collectors.joining(","))), allDBNames.size(), 0); + } + + @Test + public void testSecondCacheCheckAddDb() + throws ItemNotFoundException { + revokingDatabase = context.getBean(SnapshotManager.class); + allRevokingDBNames = parseRevokingDBNames(context); + allRevokingDBNames.add("secondCheckTestDB"); + FileUtil.createDirIfNotExists("output_revokingStore_test/database/secondCheckTestDB"); + allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list()) + .collect(Collectors.toSet()); + FileUtil.deleteDir(new File("output_revokingStore_test/database/secondCheckTestDB")); + if (CollectionUtils.isEmpty(allDBNames)) { + throw new ItemNotFoundException("No DBs found"); + } + allDBNames.removeAll(noSecondCacheDBs); + allDBNames.removeAll(CacheStrategies.CACHE_DBS); + allDBNames.retainAll(allRevokingDBNames); + org.junit.Assert.assertTrue(String.format("New added dbs %s " + + "check second cache failed!", + allDBNames.stream().collect(Collectors.joining(","))), allDBNames.size() == 1); + } + + private Set parseRevokingDBNames(TronApplicationContext context) { + SnapshotManager snapshotManager = context.getBean(SnapshotManager.class); + return snapshotManager.getDbs().stream().map(chainbase -> + chainbase.getDbName()).collect(Collectors.toSet()); + } + + @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode diff --git a/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java b/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java index bbc49835bd5..55d7c106458 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java @@ -1,31 +1,26 @@ package org.tron.core.jsonrpc; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.services.jsonrpc.types.BuildArguments; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; @Slf4j -public class BuildTransactionTest { +public class BuildTransactionTest extends BaseTest { - private static String dbPath = "output_build_transaction_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; @@ -33,24 +28,20 @@ public class BuildTransactionTest { private static final String CONTRACT_ADDRESS; private static final long SOURCE_PERCENT = 10L; - private static TronApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + @Resource + private Wallet wallet; static { + dbPath = "output_build_transaction_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; CONTRACT_ADDRESS = Wallet.getAddressPreFixString() + "f859b5c93f789f4bcffbe7cc95a71e28e5e6a5bd"; } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - + @Before + public void init() { AccountCapsule accountCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -76,17 +67,6 @@ public static void init() { new ContractCapsule(builder.build())); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testTransferContract() { BuildArguments buildArguments = new BuildArguments(); diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java index 143f257d85a..f3ad69d09a1 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java @@ -1,26 +1,35 @@ package org.tron.core.jsonrpc; +import com.alibaba.fastjson.JSON; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; import com.google.protobuf.ByteString; -import java.io.File; +import io.prometheus.client.CollectorRegistry; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.prometheus.Metrics; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.services.NodeInfoService; +import org.tron.core.services.jsonrpc.FullNodeJsonRpcHttpService; import org.tron.core.services.jsonrpc.TronJsonRpcImpl; import org.tron.core.services.jsonrpc.types.BlockResult; import org.tron.core.services.jsonrpc.types.TransactionResult; @@ -30,33 +39,35 @@ @Slf4j -public class JsonrpcServiceTest { - private static String dbPath = "output_jsonrpc_service_test"; +public class JsonrpcServiceTest extends BaseTest { private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; private static TronJsonRpcImpl tronJsonRpc; - private static TronApplicationContext context; - private static NodeInfoService nodeInfoService; + @Resource + private NodeInfoService nodeInfoService; private static BlockCapsule blockCapsule; private static TransactionCapsule transactionCapsule1; - private static TransactionCapsule transactionCapsule2; + @Resource + private Wallet wallet; + + @Resource + private FullNodeJsonRpcHttpService fullNodeJsonRpcHttpService; static { + dbPath = "output_jsonrpc_service_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(true); + CommonParameter.getInstance().setMetricsPrometheusEnable(true); + Metrics.init(); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - nodeInfoService = context.getBean("nodeInfoService", NodeInfoService.class); } - @BeforeClass - public static void init() { - Manager dbManager = context.getBean(Manager.class); - Wallet wallet = context.getBean(Wallet.class); - + @Before + public void init() { AccountCapsule accountCapsule = new AccountCapsule( ByteString.copyFromUtf8(OWNER_ADDRESS_ACCOUNT_NAME), @@ -89,8 +100,8 @@ public static void init() { transactionCapsule1 = new TransactionCapsule(transferContract1, ContractType.TransferContract); transactionCapsule1.setBlockNum(blockCapsule.getNum()); - transactionCapsule2 = - new TransactionCapsule(transferContract2, ContractType.TransferContract); + TransactionCapsule transactionCapsule2 = new TransactionCapsule(transferContract2, + ContractType.TransferContract); transactionCapsule2.setBlockNum(2L); blockCapsule.addTransaction(transactionCapsule1); @@ -107,17 +118,6 @@ public static void init() { tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testWeb3Sha3() { String result = ""; @@ -254,4 +254,40 @@ public void testGetTransactionByHash() { transactionResult.getBlockNumber()); } -} \ No newline at end of file + @Test + public void testGetBlockByNumber2() { + fullNodeJsonRpcHttpService.start(); + JsonArray params = new JsonArray(); + params.add(ByteArray.toJsonHex(blockCapsule.getNum())); + params.add(false); + JsonObject requestBody = new JsonObject(); + requestBody.addProperty("jsonrpc", "2.0"); + requestBody.addProperty("method", "eth_getBlockByNumber"); + requestBody.add("params", params); + requestBody.addProperty("id", 1); + CloseableHttpResponse response; + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpPost httpPost = new HttpPost("http://127.0.0.1:8545/jsonrpc"); + httpPost.addHeader("Content-Type", "application/json"); + httpPost.setEntity(new StringEntity(requestBody.toString())); + response = httpClient.execute(httpPost); + String resp = EntityUtils.toString(response.getEntity()); + BlockResult blockResult = JSON.parseObject(resp).getObject("result", BlockResult.class); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getNum()), + blockResult.getNumber()); + Assert.assertEquals(blockCapsule.getTransactions().size(), + blockResult.getTransactions().length); + Assert.assertEquals("0x0000000000000000", + blockResult.getNonce()); + response.close(); + Assert.assertEquals(1, CollectorRegistry.defaultRegistry.getSampleValue( + "tron:jsonrpc_service_latency_seconds_count", + new String[] {"method"}, new String[] {"eth_getBlockByNumber"}).intValue()); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } finally { + fullNodeJsonRpcHttpService.stop(); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java index 4fa40e42807..fd2b7a66d31 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java @@ -1,23 +1,19 @@ package org.tron.core.jsonrpc; -import java.io.File; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import javax.annotation.Resource; import org.junit.Test; import org.testng.Assert; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; import org.tron.common.runtime.vm.LogInfo; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionRetCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.EventBloomException; import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; @@ -27,28 +23,14 @@ import org.tron.protos.Protocol.TransactionInfo; import org.tron.protos.Protocol.TransactionInfo.Log; -public class SectionBloomStoreTest { +public class SectionBloomStoreTest extends BaseTest { - private static final String dbPath = "output-sectionBloomStore-test"; - static SectionBloomStore sectionBloomStore; - private static TronApplicationContext context; + @Resource + SectionBloomStore sectionBloomStore; static { - Args.setParam(new String[] {"--output-directory", dbPath}, - Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - sectionBloomStore = context.getBean(SectionBloomStore.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + dbPath = "output-sectionBloomStore-test"; + Args.setParam(new String[] {"--output-directory", dbPath}, Constant.TEST_CONF); } @Test diff --git a/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java b/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java index 778860b8879..05d27832e1d 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java @@ -1,21 +1,17 @@ package org.tron.core.jsonrpc; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db2.core.Chainbase.Cursor; import org.tron.core.services.NodeInfoService; import org.tron.core.services.jsonrpc.TronJsonRpcImpl; @@ -24,30 +20,28 @@ import org.tron.protos.Protocol; @Slf4j -public class WalletCursorTest { - private static String dbPath = "output_wallet_cursor_test"; +public class WalletCursorTest extends BaseTest { private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; - - private static TronApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; - private static NodeInfoService nodeInfoService; + @Resource + private Wallet wallet; + @Resource + private NodeInfoService nodeInfoService; + private static boolean init; static { + dbPath = "output_wallet_cursor_test"; Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - nodeInfoService = context.getBean("nodeInfoService", NodeInfoService.class); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - + @Before + public void init() { + if (init) { + return; + } AccountCapsule accountCapsule = new AccountCapsule( ByteString.copyFromUtf8(OWNER_ADDRESS_ACCOUNT_NAME), @@ -55,17 +49,7 @@ public static void init() { Protocol.AccountType.Normal, 10000_000_000L); dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } @Test diff --git a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java index dfe658080fc..714faea05d9 100644 --- a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java @@ -45,7 +45,7 @@ public void init() { ); CommonParameter parameter = Args.getInstance(); parameter.setNodeListenPort(port); - parameter.getSeedNode().getIpList().clear(); + parameter.getSeedNode().getAddressList().clear(); parameter.setNodeExternalIp("127.0.0.1"); context = new TronApplicationContext(DefaultConfig.class); appT = ApplicationFactory.create(context); diff --git a/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java b/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java index dadc688e5bd..a2a812ef30b 100644 --- a/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java @@ -3,7 +3,6 @@ import com.google.common.collect.Maps; import com.google.protobuf.ByteString; import io.prometheus.client.CollectorRegistry; -import java.io.File; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -12,18 +11,18 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.parameter.CommonParameter; import org.tron.common.prometheus.MetricLabels; import org.tron.common.prometheus.Metrics; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; import org.tron.consensus.dpos.DposSlot; @@ -32,34 +31,38 @@ import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.BlockGenerate; -import org.tron.core.db.Manager; import org.tron.core.net.TronNetDelegate; import org.tron.protos.Protocol; @Slf4j(topic = "metric") -public class PrometheusApiServiceTest extends BlockGenerate { - - - static ChainBaseManager chainManager; +public class PrometheusApiServiceTest extends BaseTest { static LocalDateTime localDateTime = LocalDateTime.now(); - private static DposSlot dposSlot; + @Resource + private DposSlot dposSlot; final int blocks = 512; - private final String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + private final String key = PublicMethod.getRandomPrivateKey(); private final byte[] privateKey = ByteArray.fromHexString(key); - private final AtomicInteger port = new AtomicInteger(0); + private static final AtomicInteger port = new AtomicInteger(0); private final long time = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli(); - protected String dbPath; - protected String dbEngine; - protected Manager dbManager; + @Resource private TronNetDelegate tronNetDelegate; - private TronApplicationContext context; + @Resource + private ConsensusService consensusService; + @Resource + private ChainBaseManager chainManager; - protected void initParameter(CommonParameter parameter) { + static { + dbPath = "output-prometheus-metric"; + Args.setParam(new String[] {"-d", dbPath, "-w"}, Constant.TEST_CONF); + Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); + initParameter(Args.getInstance()); + Metrics.init(); + } + + protected static void initParameter(CommonParameter parameter) { parameter.setMetricsPrometheusEnable(true); } @@ -83,47 +86,30 @@ protected void check() throws Exception { Assert.assertNull(errorLogs); } - protected void initDb() { - dbPath = "output-prometheus-metric"; - dbEngine = "LEVELDB"; - } - - @Before public void init() throws Exception { - - initDb(); - FileUtil.deleteDir(new File(dbPath)); logger.info("Full node running."); - Args.setParam(new String[] {"-d", dbPath, "-w"}, Constant.TEST_CONF); - Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); - initParameter(Args.getInstance()); - Metrics.init(); - context = new TronApplicationContext(DefaultConfig.class); - - dbManager = context.getBean(Manager.class); - setManager(dbManager); - dposSlot = context.getBean(DposSlot.class); - ConsensusService consensusService = context.getBean(ConsensusService.class); consensusService.start(); - chainManager = dbManager.getChainBaseManager(); - tronNetDelegate = context.getBean(TronNetDelegate.class); - } + chainBaseManager = dbManager.getChainBaseManager(); + byte[] address = PublicMethod.getAddressByteByPrivateKey(key); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainBaseManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainBaseManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainBaseManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } private void generateBlock(Map witnessAndAccount) throws Exception { BlockCapsule block = createTestBlockCapsule( - chainManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() + 3000, - chainManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1, - chainManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(), + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() + 3000, + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1, + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(), witnessAndAccount); tronNetDelegate.processBlock(block, false); @@ -136,8 +122,8 @@ public void testMetric() throws Exception { Assert.assertNotNull(ecKey); byte[] address = ecKey.getAddress(); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); - chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); - chainManager.addWitness(ByteString.copyFrom(address)); + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); + chainBaseManager.addWitness(ByteString.copyFrom(address)); Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); @@ -152,7 +138,7 @@ public void testMetric() throws Exception { } private Map addTestWitnessAndAccount() { - chainManager.getWitnesses().clear(); + chainBaseManager.getWitnesses().clear(); return IntStream.range(0, 2) .mapToObj( i -> { @@ -161,12 +147,12 @@ private Map addTestWitnessAndAccount() { ByteString address = ByteString.copyFrom(ecKey.getAddress()); WitnessCapsule witnessCapsule = new WitnessCapsule(address); - chainManager.getWitnessStore().put(address.toByteArray(), witnessCapsule); - chainManager.addWitness(address); + chainBaseManager.getWitnessStore().put(address.toByteArray(), witnessCapsule); + chainBaseManager.addWitness(address); AccountCapsule accountCapsule = new AccountCapsule(Protocol.Account.newBuilder().setAddress(address).build()); - chainManager.getAccountStore().put(address.toByteArray(), accountCapsule); + chainBaseManager.getAccountStore().put(address.toByteArray(), accountCapsule); return Maps.immutableEntry(address, privateKey); }) diff --git a/framework/src/test/java/org/tron/core/net/BaseNet.java b/framework/src/test/java/org/tron/core/net/BaseNet.java index bb7ca85ef7f..805f8aa76a4 100644 --- a/framework/src/test/java/org/tron/core/net/BaseNet.java +++ b/framework/src/test/java/org/tron/core/net/BaseNet.java @@ -19,8 +19,8 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; @@ -34,20 +34,20 @@ import org.tron.core.services.RpcApiService; @Slf4j -public abstract class BaseNet { +public class BaseNet { private static String dbPath = "output-net"; private static String dbDirectory = "net-database"; private static String indexDirectory = "net-index"; private static int port = 10000; - protected TronApplicationContext context; + protected static TronApplicationContext context; - private RpcApiService rpcApiService; - private Application appT; - private TronNetDelegate tronNetDelegate; + private static RpcApiService rpcApiService; + private static Application appT; + private static TronNetDelegate tronNetDelegate; - private ExecutorService executorService = Executors.newFixedThreadPool(1); + private static ExecutorService executorService = Executors.newFixedThreadPool(1); public static Channel connect(ByteToMessageDecoder decoder) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(1); @@ -73,49 +73,51 @@ protected void initChannel(Channel ch) throws Exception { return b.connect(Constant.LOCAL_HOST, port).sync().channel(); } - @Before - public void init() throws Exception { - executorService.execute(new Runnable() { - @Override - public void run() { - logger.info("Full node running."); - Args.setParam( - new String[]{ - "--output-directory", dbPath, - "--storage-db-directory", dbDirectory, - "--storage-index-directory", indexDirectory - }, - "config.conf" - ); - CommonParameter parameter = Args.getInstance(); - parameter.setNodeListenPort(port); - parameter.getSeedNode().getIpList().clear(); - parameter.setNodeExternalIp(Constant.LOCAL_HOST); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - rpcApiService = context.getBean(RpcApiService.class); - appT.addService(rpcApiService); - appT.initServices(parameter); - appT.startServices(); - appT.startup(); - tronNetDelegate = context.getBean(TronNetDelegate.class); - rpcApiService.blockUntilShutdown(); + @BeforeClass + public static void init() throws Exception { + executorService.execute(() -> { + logger.info("Full node running."); + Args.setParam( + new String[]{ + "--output-directory", dbPath, + "--storage-db-directory", dbDirectory, + "--storage-index-directory", indexDirectory + }, + "config.conf" + ); + CommonParameter parameter = Args.getInstance(); + parameter.setNodeListenPort(port); + parameter.getSeedNode().getAddressList().clear(); + parameter.setNodeExternalIp(Constant.LOCAL_HOST); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + rpcApiService = context.getBean(RpcApiService.class); + appT.addService(rpcApiService); + appT.initServices(parameter); + appT.startServices(); + appT.startup(); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + //ignore } + tronNetDelegate = context.getBean(TronNetDelegate.class); + rpcApiService.blockUntilShutdown(); }); int tryTimes = 0; - while (++tryTimes < 100 && tronNetDelegate == null) { - Thread.sleep(3000); - } + do { + Thread.sleep(3000); //coverage consumerInvToSpread,consumerInvToFetch in AdvService.init + } while (++tryTimes < 100 && tronNetDelegate == null); } - @After - public void destroy() { + @AfterClass + public static void destroy() { Collection peerConnections = ReflectUtils .invokeMethod(tronNetDelegate, "getActivePeer"); for (PeerConnection peer : peerConnections) { peer.getChannel().close(); } - + Args.clearParam(); context.destroy(); FileUtil.deleteDir(new File(dbPath)); } diff --git a/framework/src/test/java/org/tron/core/net/MessageTest.java b/framework/src/test/java/org/tron/core/net/MessageTest.java index 0400d16b669..5b81d18a599 100644 --- a/framework/src/test/java/org/tron/core/net/MessageTest.java +++ b/framework/src/test/java/org/tron/core/net/MessageTest.java @@ -1,10 +1,17 @@ package org.tron.core.net; +import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; +import org.tron.common.overlay.message.Message; import org.tron.core.exception.P2pException; import org.tron.core.net.message.MessageTypes; +import org.tron.core.net.message.adv.FetchInvDataMessage; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.message.adv.TransactionsMessage; import org.tron.core.net.message.base.DisconnectMessage; +import org.tron.core.net.service.statistics.MessageStatistics; +import org.tron.protos.Protocol.Inventory.InventoryType; import org.tron.protos.Protocol.ReasonCode; public class MessageTest { @@ -35,4 +42,91 @@ public void test2() throws Exception { System.out.println("spend time : " + (endTime - startTime)); } + @Test + public void testMessageStatistics() { + MessageStatistics messageStatistics = new MessageStatistics(); + Message message1 = new Message(MessageTypes.P2P_HELLO.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message2 = new Message(MessageTypes.P2P_PING.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message3 = new Message(MessageTypes.P2P_PONG.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message4 = new Message(MessageTypes.P2P_DISCONNECT.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message5 = new Message(MessageTypes.SYNC_BLOCK_CHAIN.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message6 = new Message(MessageTypes.BLOCK_CHAIN_INVENTORY.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message7 = new Message(MessageTypes.TRX.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message8 = new Message(MessageTypes.BLOCK.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + InventoryMessage message9 = new InventoryMessage(new ArrayList<>(), InventoryType.TRX); + FetchInvDataMessage message10 = new FetchInvDataMessage(new ArrayList<>(), InventoryType.TRX); + TransactionsMessage message11 = new TransactionsMessage(new ArrayList<>()); + + messageStatistics.addTcpInMessage(message1); + messageStatistics.addTcpOutMessage(message1); + messageStatistics.addTcpInMessage(message2); + messageStatistics.addTcpOutMessage(message2); + messageStatistics.addTcpInMessage(message3); + messageStatistics.addTcpOutMessage(message3); + messageStatistics.addTcpInMessage(message4); + messageStatistics.addTcpOutMessage(message4); + messageStatistics.addTcpInMessage(message5); + messageStatistics.addTcpOutMessage(message5); + try { + Thread.sleep(2000);// so that gap > 1 in MessageCount.update method + } catch (InterruptedException e) { + //ignore + } + messageStatistics.addTcpInMessage(message6); + messageStatistics.addTcpOutMessage(message6); + messageStatistics.addTcpInMessage(message7); + messageStatistics.addTcpOutMessage(message7); + messageStatistics.addTcpInMessage(message8); + messageStatistics.addTcpOutMessage(message8); + messageStatistics.addTcpInMessage(message9); + messageStatistics.addTcpOutMessage(message9); + messageStatistics.addTcpInMessage(message10); + messageStatistics.addTcpOutMessage(message10); + messageStatistics.addTcpInMessage(message11); + messageStatistics.addTcpOutMessage(message11); + + Assert.assertEquals(11, messageStatistics.tronInMessage.getTotalCount()); + Assert.assertEquals(11, messageStatistics.tronOutMessage.getTotalCount()); + } + } diff --git a/framework/src/test/java/org/tron/core/net/NodeTest.java b/framework/src/test/java/org/tron/core/net/NodeTest.java new file mode 100644 index 00000000000..5f0e2c38b2b --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/NodeTest.java @@ -0,0 +1,99 @@ +package org.tron.core.net; + +import static org.tron.core.net.message.handshake.HelloMessage.getEndpointFromNode; + +import com.typesafe.config.Config; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.Constant; +import org.tron.core.config.Configuration; +import org.tron.core.config.args.Args; +import org.tron.p2p.discover.Node; +import org.tron.p2p.dns.update.DnsType; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.utils.NetUtil; +import org.tron.protos.Discover.Endpoint; + +@Slf4j +public class NodeTest { + + @Test + public void testIpV4() { + InetSocketAddress address1 = NetUtil.parseInetSocketAddress("192.168.0.1:18888"); + Assert.assertNotNull(address1); + try { + NetUtil.parseInetSocketAddress("192.168.0.1"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + } + + @Test + public void testIpV6() { + try { + NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb:18888"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + InetSocketAddress address2 = NetUtil.parseInetSocketAddress("[fe80::216:3eff:fe0e:23bb]:18888"); + Assert.assertNotNull(address2); + try { + NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + } + + @Test + public void testIpStack() { + Set ipSet = new HashSet<>(Collections.singletonList("192.168.0.1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.singletonList("127.0.0.1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.singletonList("fe80:0:0:0:0:0:0:1")); + Assert.assertFalse(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Arrays.asList("127.0.0.1", "fe80:0:0:0:0:0:0:1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.emptyList()); + Assert.assertFalse(TronNetService.hasIpv4Stack(ipSet)); + } + + @Test + public void testEndpointFromNode() { + Node node = new Node(null, null, null, 18888); + Endpoint endpoint = getEndpointFromNode(node); + Assert.assertTrue(endpoint.getNodeId().isEmpty()); + Assert.assertTrue(endpoint.getAddress().isEmpty()); + Assert.assertTrue(endpoint.getAddressIpv6().isEmpty()); + } + + @Test + public void testPublishConfig() { + Config config = Configuration.getByFileName(Constant.TEST_CONF, Constant.TEST_CONF); + + PublishConfig publishConfig = new PublishConfig(); + Assert.assertFalse(publishConfig.isDnsPublishEnable()); + + publishConfig.setDnsPublishEnable(true); + Assert.assertTrue(publishConfig.isDnsPublishEnable()); + Args.loadDnsPublishParameters(config, publishConfig); + Assert.assertTrue(publishConfig.isDnsPublishEnable()); + Assert.assertEquals(5, publishConfig.getMaxMergeSize()); + Assert.assertEquals(DnsType.AwsRoute53, publishConfig.getDnsType()); + } + + @After + public void destroy() { + Args.clearParam(); + } +} diff --git a/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java new file mode 100644 index 00000000000..0008ec315d5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java @@ -0,0 +1,111 @@ +package org.tron.core.net; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.service.statistics.PeerStatistics; +import org.tron.protos.Protocol; + +public class P2pEventHandlerImplTest { + + @Test + public void testProcessInventoryMessage() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + CommonParameter parameter = CommonParameter.getInstance(); + parameter.setMaxTps(10); + + PeerStatistics peerStatistics = new PeerStatistics(); + + PeerConnection peer = mock(PeerConnection.class); + Mockito.when(peer.getPeerStatistics()).thenReturn(peerStatistics); + + P2pEventHandlerImpl p2pEventHandler = new P2pEventHandlerImpl(); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + int count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement + .getCount(10); + + Assert.assertEquals(0, count); + + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + InventoryMessage msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(10, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(110, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(110, count); + + list.clear(); + for (int i = 0; i < 200; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.BLOCK); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInBlockInventoryElement.getCount(10); + + Assert.assertEquals(200, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.BLOCK); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInBlockInventoryElement.getCount(10); + + Assert.assertEquals(300, count); + + } +} diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java index ff6203ee870..57c27bc2382 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java @@ -1,19 +1,23 @@ package org.tron.core.net.messagehandler; +import static org.junit.Assert.assertEquals; + import com.google.common.collect.ImmutableList; import com.google.protobuf.ByteString; + import java.lang.reflect.Field; import java.net.InetSocketAddress; import java.util.List; -import org.junit.After; -import org.junit.Assert; +import javax.annotation.Resource; + +import lombok.extern.slf4j.Slf4j; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; @@ -24,25 +28,30 @@ import org.tron.protos.Protocol.Inventory.InventoryType; import org.tron.protos.Protocol.Transaction; -public class BlockMsgHandlerTest { +@Slf4j +public class BlockMsgHandlerTest extends BaseTest { - protected TronApplicationContext context; + @Resource private BlockMsgHandler handler; + @Resource private PeerConnection peer; /** * init context. */ - @Before - public void init() throws Exception { - Args.setParam(new String[]{"--output-directory", "output-directory", "--debug"}, + @BeforeClass + public static void init() { + dbPath = "output_blockmsghandler_test"; + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - handler = context.getBean(BlockMsgHandler.class); - peer = context.getBean(PeerConnection.class); + + } + + @Before + public void before() throws Exception { Channel c1 = new Channel(); InetSocketAddress a1 = new InetSocketAddress("100.1.1.1", 100); - Field field = c1.getClass().getDeclaredField("inetAddress"); + Field field = c1.getClass().getDeclaredField("inetAddress"); field.setAccessible(true); field.set(c1, a1.getAddress()); peer.setChannel(c1); @@ -58,7 +67,7 @@ public void testProcessMessage() { msg = new BlockMessage(blockCapsule); handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("no request")); + assertEquals("no request", e.getMessage()); } try { @@ -78,7 +87,7 @@ public void testProcessMessage() { handler.processMessage(peer, msg); } catch (P2pException e) { //System.out.println(e); - Assert.assertTrue(e.getMessage().equals("block size over limit")); + assertEquals("block size over limit", e.getMessage()); } try { @@ -90,7 +99,7 @@ public void testProcessMessage() { handler.processMessage(peer, msg); } catch (P2pException e) { //System.out.println(e); - Assert.assertTrue(e.getMessage().equals("block time error")); + assertEquals("block time error", e.getMessage()); } try { @@ -112,13 +121,7 @@ public void testProcessMessage() { .put(new Item(msg.getBlockId(), InventoryType.BLOCK), System.currentTimeMillis()); handler.processMessage(peer, msg); } catch (NullPointerException | P2pException e) { - System.out.println(e); + logger.error("error", e); } } - - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java new file mode 100644 index 00000000000..215b5f495ad --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java @@ -0,0 +1,113 @@ +package org.tron.core.net.messagehandler; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.TronNetService; +import org.tron.core.net.message.keepalive.PingMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; + +public class MessageHandlerTest { + + private static TronApplicationContext context; + private PeerConnection peer; + private static P2pEventHandlerImpl p2pEventHandler; + private static ApplicationContext ctx; + private static String dbPath = "output-message-handler-test"; + + + @BeforeClass + public static void init() throws Exception { + Args.setParam(new String[] {"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + + TronNetService tronNetService = context.getBean(TronNetService.class); + Parameter.p2pConfig = new P2pConfig(); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", Parameter.p2pConfig); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Before + public void clearPeers() { + try { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + } catch (NoSuchFieldException | IllegalAccessException e) { + //ignore + } + } + + @Test + public void testPbft() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + p2pEventHandler.onConnect(c1); + Assert.assertEquals(1, PeerManager.getPeers().size()); + Assert.assertFalse(c1.isDisconnect()); + + peer = PeerManager.getPeers().get(0); + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + PbftMessage pbftMessage = PbftMessage.fullNodePrePrepareBlockMsg(blockCapsule, 0L); + p2pEventHandler.onMessage(peer.getChannel(), pbftMessage.getSendBytes()); + + InetSocketAddress a2 = new InetSocketAddress("127.0.0.1", 10002); + Channel c2 = mock(Channel.class); + Mockito.when(c2.getInetSocketAddress()).thenReturn(a2); + Mockito.when(c2.getInetAddress()).thenReturn(a2.getAddress()); + p2pEventHandler.onMessage(c2, pbftMessage.getSendBytes()); + + Assert.assertEquals(1, PeerManager.getPeers().size()); + } + + @Test + public void testPing() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + + PingMessage pingMessage = new PingMessage(); + p2pEventHandler.onMessage(c1, pingMessage.getSendBytes()); + Assert.assertEquals(1, PeerManager.getPeers().size()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java index a0c37d246da..2dbad09c655 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java @@ -1,24 +1,75 @@ package org.tron.core.net.messagehandler; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; import java.util.ArrayList; +import java.util.List; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; import org.tron.core.net.message.sync.SyncBlockChainMessage; import org.tron.core.net.peer.PeerConnection; +import org.tron.p2p.connection.Channel; public class SyncBlockChainMsgHandlerTest { - private SyncBlockChainMsgHandler handler = new SyncBlockChainMsgHandler(); - private PeerConnection peer = new PeerConnection(); + private TronApplicationContext context; + private SyncBlockChainMsgHandler handler; + private PeerConnection peer; + private String dbPath = "output-sync-chain-test"; + + @Before + public void init() throws Exception { + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + handler = context.getBean(SyncBlockChainMsgHandler.class); + peer = context.getBean(PeerConnection.class); + Channel c1 = new Channel(); + InetSocketAddress a1 = new InetSocketAddress("100.1.1.1", 100); + Field field = c1.getClass().getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(c1, a1); + + field = c1.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c1, a1.getAddress()); + + peer.setChannel(c1); + } @Test - public void testProcessMessage() { + public void testProcessMessage() throws Exception { try { handler.processMessage(peer, new SyncBlockChainMessage(new ArrayList<>())); } catch (P2pException e) { Assert.assertTrue(e.getMessage().equals("SyncBlockChain blockIds is empty")); } + + List blockIds = new ArrayList<>(); + blockIds.add(new BlockCapsule.BlockId()); + SyncBlockChainMessage message = new SyncBlockChainMessage(blockIds); + Method method = handler.getClass().getDeclaredMethod( + "check", PeerConnection.class, SyncBlockChainMessage.class); + method.setAccessible(true); + boolean f = (boolean)method.invoke(handler, peer, message); + Assert.assertTrue(!f); + } + + @After + public void destroy() { + Args.clearParam(); + FileUtil.deleteDir(new File(dbPath)); } } diff --git a/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java b/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java index a6189346ae5..78db0398755 100644 --- a/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java @@ -1,23 +1,18 @@ package org.tron.core.net.services; import com.google.common.collect.Lists; - -import java.io.File; import java.util.List; -import org.junit.After; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.net.P2pEventHandlerImpl; import org.tron.core.net.message.adv.BlockMessage; import org.tron.core.net.message.adv.TransactionMessage; import org.tron.core.net.peer.Item; @@ -27,32 +22,21 @@ import org.tron.protos.Protocol; import org.tron.protos.Protocol.Inventory.InventoryType; -public class AdvServiceTest { +public class AdvServiceTest extends BaseTest { - protected TronApplicationContext context; + @Resource private AdvService service; + @Resource private PeerConnection peer; - private P2pEventHandlerImpl p2pEventHandler; - private String dbPath = "output-adv-service-test"; /** * init context. */ - @Before - public void init() { + @BeforeClass + public static void init() { + dbPath = "output-adv-service-test"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - service = context.getBean(AdvService.class); - } - - /** - * destroy. - */ - @After - public void destroy() { - Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } @Test @@ -84,9 +68,6 @@ private void testAddInv() { private void testBroadcast() { try { - peer = context.getBean(PeerConnection.class); - p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); - List peers = Lists.newArrayList(); peers.add(peer); ReflectUtils.setFieldValue(P2pEventHandler.class, "peers", peers); @@ -96,6 +77,9 @@ private void testBroadcast() { service.broadcast(msg); Item item = new Item(blockCapsule.getBlockId(), InventoryType.BLOCK); Assert.assertNotNull(service.getMessage(item)); + peer.checkAndPutAdvInvRequest(item, System.currentTimeMillis()); + boolean res = peer.checkAndPutAdvInvRequest(item, System.currentTimeMillis()); + Assert.assertFalse(res); } catch (NullPointerException e) { System.out.println(e); } diff --git a/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java b/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java new file mode 100644 index 00000000000..aa42e0fcb89 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java @@ -0,0 +1,70 @@ +package org.tron.core.net.services; + +import java.io.File; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.TronNetService; +import org.tron.core.net.service.effective.EffectiveCheckService; +import org.tron.p2p.P2pConfig; + +public class EffectiveCheckServiceTest { + + protected TronApplicationContext context; + private EffectiveCheckService service; + private String dbPath = "output-effective-service-test"; + + @Before + public void init() { + Args.setParam(new String[] {"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + service = context.getBean(EffectiveCheckService.class); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Test + public void testNoIpv4() throws Exception { + TronNetService tronNetService = context.getBean(TronNetService.class); + Method privateMethod = tronNetService.getClass() + .getDeclaredMethod("updateConfig", P2pConfig.class); + privateMethod.setAccessible(true); + P2pConfig config = new P2pConfig(); + config.setIp(null); + P2pConfig newConfig = (P2pConfig) privateMethod.invoke(tronNetService, config); + Assert.assertNotNull(newConfig.getIp()); + } + + @Test + public void testFind() { + TronNetService tronNetService = context.getBean(TronNetService.class); + P2pConfig p2pConfig = new P2pConfig(); + p2pConfig.setIp("127.0.0.1"); + p2pConfig.setPort(34567); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", p2pConfig); + TronNetService.getP2pService().start(p2pConfig); + + service.triggerNext(); + Assert.assertNull(service.getCur()); + + ReflectUtils.invokeMethod(service, "resetCount"); + InetSocketAddress cur = new InetSocketAddress("192.168.0.1", 34567); + service.setCur(cur); + service.onDisconnect(cur); + } +} diff --git a/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java new file mode 100644 index 00000000000..4f074b2c825 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java @@ -0,0 +1,269 @@ +package org.tron.core.net.services; + +import static org.mockito.Mockito.mock; +import static org.tron.core.net.message.handshake.HelloMessage.getEndpointFromNode; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.TronNetService; +import org.tron.core.net.message.handshake.HelloMessage; +import org.tron.core.net.message.keepalive.PingMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; +import org.tron.protos.Discover.Endpoint; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.HelloMessage.Builder; + +public class HandShakeServiceTest { + + private static TronApplicationContext context; + private PeerConnection peer; + private static P2pEventHandlerImpl p2pEventHandler; + private static ApplicationContext ctx; + private static String dbPath = "output-message-handler-test"; + + + @BeforeClass + public static void init() throws Exception { + Args.setParam(new String[] {"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + + TronNetService tronNetService = context.getBean(TronNetService.class); + Parameter.p2pConfig = new P2pConfig(); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", Parameter.p2pConfig); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Before + public void clearPeers() { + try { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + } catch (NoSuchFieldException | IllegalAccessException e) { + //ignore + } + } + + @Test + public void testOkHelloMessage() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + //ok + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); + HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + + //dup hello message + peer.setHelloMessageReceive(helloMessage); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + + //dup peer + peer.setHelloMessageReceive(null); + Mockito.when(c1.isDisconnect()).thenReturn(true); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } + + @Test + public void testInvalidHelloMessage() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + //block hash is empty + try { + BlockCapsule.BlockId hid = ChainBaseManager.getChainBaseManager().getHeadBlockId(); + Protocol.HelloMessage.BlockId hBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(ByteString.copyFrom(new byte[0])) + .setNumber(hid.getNum()) + .build(); + builder.setHeadBlockId(hBlockId); + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertTrue(!helloMessage.valid()); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testRelayHelloMessage() throws NoSuchMethodException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + //address is empty + Args.getInstance().fastForward = true; + clearPeers(); + Node node2 = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, 10002); + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + Args.getInstance().fastForward = false; + } + + @Test + public void testLowAndGenesisBlockNum() throws NoSuchMethodException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + Node node2 = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, 10002); + + //lowestBlockNum > headBlockNum + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + builder.setLowestBlockNum(ChainBaseManager.getChainBaseManager().getLowestBlockNum() + 1); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + + //genesisBlock is not equal + builder = getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + BlockCapsule.BlockId gid = ChainBaseManager.getChainBaseManager().getGenesisBlockId(); + Protocol.HelloMessage.BlockId gBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(gid.getByteString()) + .setNumber(gid.getNum() + 1) + .build(); + builder.setGenesisBlockId(gBlockId); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + + //solidityBlock <= us, but not contained + builder = getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + BlockCapsule.BlockId sid = ChainBaseManager.getChainBaseManager().getSolidBlockId(); + + Random gen = new Random(); + byte[] randomHash = new byte[Sha256Hash.LENGTH]; + gen.nextBytes(randomHash); + + Protocol.HelloMessage.BlockId sBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(ByteString.copyFrom(randomHash)) + .setNumber(sid.getNum()) + .build(); + builder.setSolidBlockId(sBlockId); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + } + + private Protocol.HelloMessage.Builder getHelloMessageBuilder(Node from, long timestamp, + ChainBaseManager chainBaseManager) { + Endpoint fromEndpoint = getEndpointFromNode(from); + + BlockCapsule.BlockId gid = chainBaseManager.getGenesisBlockId(); + Protocol.HelloMessage.BlockId gBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(gid.getByteString()) + .setNumber(gid.getNum()) + .build(); + + BlockCapsule.BlockId sid = chainBaseManager.getSolidBlockId(); + Protocol.HelloMessage.BlockId sBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(sid.getByteString()) + .setNumber(sid.getNum()) + .build(); + + BlockCapsule.BlockId hid = chainBaseManager.getHeadBlockId(); + Protocol.HelloMessage.BlockId hBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(hid.getByteString()) + .setNumber(hid.getNum()) + .build(); + Builder builder = Protocol.HelloMessage.newBuilder(); + builder.setFrom(fromEndpoint); + builder.setVersion(Args.getInstance().getNodeP2pVersion()); + builder.setTimestamp(timestamp); + builder.setGenesisBlockId(gBlockId); + builder.setSolidBlockId(sBlockId); + builder.setHeadBlockId(hBlockId); + builder.setNodeType(chainBaseManager.getNodeType().getType()); + builder.setLowestBlockNum(chainBaseManager.isLiteNode() + ? chainBaseManager.getLowestBlockNum() : 0); + + return builder; + } +} diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java index b4deb6aff4b..a5b676d0144 100644 --- a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java @@ -2,25 +2,22 @@ import com.google.common.collect.Lists; import com.google.protobuf.ByteString; -import java.io.File; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; +import javax.annotation.Resource; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.common.utils.ReflectUtils; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.net.P2pEventHandlerImpl; import org.tron.core.net.message.adv.BlockMessage; @@ -29,33 +26,23 @@ import org.tron.core.net.service.relay.RelayService; import org.tron.protos.Protocol; -public class RelayServiceTest { +public class RelayServiceTest extends BaseTest { - protected TronApplicationContext context; + @Resource private RelayService service; - private ChainBaseManager chainBaseManager; + @Resource private PeerConnection peer; + @Resource private P2pEventHandlerImpl p2pEventHandler; - private String dbPath = "output-relay-service-test"; /** * init context. */ - @Before - public void init() { + @BeforeClass + public static void init() { + dbPath = "output-relay-service-test"; Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - service = context.getBean(RelayService.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); - } - - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test @@ -83,31 +70,29 @@ public void testGetNextWitnesses() throws Exception { method.setAccessible(true); Set s1 = (Set) method.invoke( service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 3); - Assert.assertEquals(s1.size(), 3); + Assert.assertEquals(3, s1.size()); assertContains(s1, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); assertContains(s1, "A0807337F180B62A77576377C1D0C9C24DF5C0DD62"); assertContains(s1, "A05430A3F089154E9E182DDD6FE136A62321AF22A7"); Set s2 = (Set) method.invoke( service, getFromHexString("A0FAB5FBF6AFB681E4E37E9D33BDDB7E923D6132E5"), 3); - Assert.assertEquals(s2.size(), 3); + Assert.assertEquals(3, s2.size()); assertContains(s2, "A014EEBE4D30A6ACB505C8B00B218BDC4733433C68"); assertContains(s2, "A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"); assertContains(s2, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); Set s3 = (Set) method.invoke( service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 1); - Assert.assertEquals(s3.size(), 1); + Assert.assertEquals(1, s3.size()); assertContains(s3, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); } private void testBroadcast() { try { - peer = context.getBean(PeerConnection.class); peer.setAddress(getFromHexString("A0299F3DB80A24B20A254B89CE639D59132F157F13")); peer.setNeedSyncFromPeer(false); peer.setNeedSyncFromUs(false); - p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); List peers = Lists.newArrayList(); peers.add(peer); diff --git a/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java new file mode 100644 index 00000000000..4eebb7da12c --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java @@ -0,0 +1,222 @@ +package org.tron.core.net.services; + +import static org.mockito.Mockito.mock; + +import com.google.common.cache.Cache; +import java.io.File; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.message.adv.BlockMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.peer.TronState; +import org.tron.core.net.service.sync.SyncService; +import org.tron.p2p.connection.Channel; +import org.tron.protos.Protocol; + +public class SyncServiceTest { + protected TronApplicationContext context; + private SyncService service; + private PeerConnection peer; + private P2pEventHandlerImpl p2pEventHandler; + private ApplicationContext ctx; + private String dbPath = "output-sync-service-test"; + private InetSocketAddress inetSocketAddress = + new InetSocketAddress("127.0.0.2", 10001); + + public SyncServiceTest() { + } + + /** + * init context. + */ + @Before + public void init() throws Exception { + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + service = context.getBean(SyncService.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + } + + /** + * destroy. + */ + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Test + public void testStartSync() { + try { + ReflectUtils.setFieldValue(service, "fetchFlag", true); + ReflectUtils.setFieldValue(service, "handleFlag", true); + service.init(); + Assert.assertTrue((boolean) ReflectUtils.getFieldObject(service, "fetchFlag")); + Assert.assertTrue((boolean) ReflectUtils.getFieldObject(service, "handleFlag")); + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + + peer.setChannel(c1); + + service.startSync(peer); + + ReflectUtils.setFieldValue(peer, "tronState", TronState.SYNCING); + + service.startSync(peer); + } catch (Exception e) { + // no need to deal with + } + service.close(); + } + + @Test + public void testProcessBlock() { + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + peer.setChannel(c1); + service.processBlock(peer, + new BlockMessage(new BlockCapsule(Protocol.Block.newBuilder().build()))); + boolean fetchFlag = (boolean) ReflectUtils.getFieldObject(service, "fetchFlag"); + boolean handleFlag = (boolean) ReflectUtils.getFieldObject(service, "handleFlag"); + Assert.assertTrue(fetchFlag); + Assert.assertTrue(handleFlag); + } + + @Test + public void testOnDisconnect() { + Cache requestBlockIds = + (Cache) ReflectUtils.getFieldObject(service, "requestBlockIds"); + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(inetSocketAddress); + Mockito.when(c1.getInetAddress()).thenReturn(inetSocketAddress.getAddress()); + peer.setChannel(c1); + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + requestBlockIds.put(blockId, peer); + peer.getSyncBlockRequested().put(blockId, System.currentTimeMillis()); + service.onDisconnect(peer); + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) == null); + } + + @Test + public void testStartFetchSyncBlock() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + + Method method = service.getClass().getDeclaredMethod("startFetchSyncBlock"); + method.setAccessible(true); + + Cache requestBlockIds = + (Cache) + ReflectUtils.getFieldObject(service, "requestBlockIds"); + + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(inetSocketAddress); + Mockito.when(c1.getInetAddress()).thenReturn(inetSocketAddress.getAddress()); + + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + + peer.getSyncBlockToFetch().add(blockId); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockToFetch().size() == 1); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + + peer.setFetchAble(true); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockToFetch().size() == 1); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) != null); + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) != null); + + peer.getSyncBlockRequested().remove(blockId); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + } + + @Test + public void testHandleSyncBlock() throws Exception { + + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + Method method = service.getClass().getDeclaredMethod("handleSyncBlock"); + method.setAccessible(true); + + Map blockJustReceived = + (Map) + ReflectUtils.getFieldObject(service, "blockJustReceived"); + Protocol.BlockHeader.raw.Builder blockHeaderRawBuild = Protocol.BlockHeader.raw.newBuilder(); + Protocol.BlockHeader.raw blockHeaderRaw = blockHeaderRawBuild + .setNumber(100000) + .build(); + + // block header + Protocol.BlockHeader.Builder blockHeaderBuild = Protocol.BlockHeader.newBuilder(); + Protocol.BlockHeader blockHeader = blockHeaderBuild.setRawData(blockHeaderRaw).build(); + + BlockCapsule blockCapsule = new BlockCapsule(Protocol.Block.newBuilder() + .setBlockHeader(blockHeader).build()); + + BlockCapsule.BlockId blockId = blockCapsule.getBlockId(); + + + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + blockJustReceived.put(new BlockMessage(blockCapsule), peer); + + peer.getSyncBlockToFetch().add(blockId); + + Cache requestBlockIds = + (Cache) + ReflectUtils.getFieldObject(service, "requestBlockIds"); + + requestBlockIds.put(blockId, peer); + + method.invoke(service); + + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) == null); + } +} diff --git a/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java b/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java index 16c1205a818..61ce5ec3625 100755 --- a/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java +++ b/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java @@ -3,60 +3,44 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.protobuf.ByteString; -import java.io.File; import java.io.IOException; +import java.util.Objects; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; -import org.junit.After; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.BlockGenerate; import org.tron.core.db.CommonDataBase; -import org.tron.core.db.Manager; import org.tron.core.db2.ISession; -import org.tron.core.exception.HeaderNotFound; import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; import org.tron.core.store.DynamicPropertiesStore; @Slf4j -public class PbftApiTest extends BlockGenerate { +public class PbftApiTest extends BaseTest { + @Resource + private HttpApiOnPBFTService httpApiOnPBFTService; - private static Manager dbManager; - private static TronApplicationContext context; - private static String dbPath = "output_pbftAPI_test"; - - @Before - public void init() { + @BeforeClass + public static void init() { + dbPath = "output_pbftAPI_test"; Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - setManager(dbManager); - } - - @After - public void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test - public void pbftapi() throws IOException, InterruptedException, HeaderNotFound { + public void pbftapi() throws IOException { ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); DynamicPropertiesStore dynamicPropertiesStore = chainBaseManager.getDynamicPropertiesStore(); CommonDataBase commonDataBase = chainBaseManager.getCommonDataBase(); @@ -75,17 +59,18 @@ public void pbftapi() throws IOException, InterruptedException, HeaderNotFound { Assert.assertTrue(dynamicPropertiesStore.getLatestBlockHeaderNumber() >= 10); commonDataBase.saveLatestPbftBlockNum(6); - HttpApiOnPBFTService httpApiOnPBFTService = context.getBean(HttpApiOnPBFTService.class); httpApiOnPBFTService.start(); - CloseableHttpResponse response = null; + CloseableHttpResponse response; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet("http://127.0.0.1:8092/walletpbft/getnowblock"); response = httpClient.execute(httpGet); String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSON.parseObject(responseString); - long num = jsonObject.getJSONObject("block_header").getJSONObject("raw_data") - .getLongValue("number"); - Assert.assertEquals(commonDataBase.getLatestPbftBlockNum(), num); + if (Objects.nonNull(jsonObject)) { + long num = jsonObject.getJSONObject("block_header").getJSONObject("raw_data") + .getLongValue("number"); + Assert.assertEquals(commonDataBase.getLatestPbftBlockNum(), num); + } response.close(); } httpApiOnPBFTService.stop(); diff --git a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java index dc99cb8f4af..e2ea87a1d0f 100644 --- a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java @@ -1,7 +1,7 @@ package org.tron.core.services; import static org.tron.common.utils.Commons.decodeFromBase58Check; -import static stest.tron.wallet.common.client.Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET; +import static org.tron.common.utils.client.Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET; import com.google.protobuf.ByteString; import io.grpc.ManagedChannelBuilder; @@ -33,7 +33,7 @@ public DelegationServiceTest(TronApplicationContext context) { public static void testGrpc() { WalletBlockingStub walletStub = WalletGrpc .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build()); BytesMessage.Builder builder = BytesMessage.newBuilder(); builder.setValue(ByteString.copyFromUtf8("TLTDZBcPoJ8tZ6TTEeEqEvwYFk2wgotSfD")); diff --git a/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java b/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java index 6a8e211a1ed..d442a5826f7 100644 --- a/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java @@ -11,9 +11,10 @@ import org.tron.common.application.TronApplicationContext; import org.tron.common.entity.NodeInfo; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.client.Configuration; import org.tron.core.capsule.BlockCapsule; import org.tron.program.Version; -import stest.tron.wallet.common.client.Configuration; + @Slf4j public class NodeInfoServiceTest { @@ -44,7 +45,7 @@ public void test() { public void testGrpc() { WalletBlockingStub walletStub = WalletGrpc .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build()); logger.info("getNodeInfo: {}", walletStub.getNodeInfo(EmptyMessage.getDefaultInstance())); } diff --git a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java index 7978d98a9fe..53c97f07b2a 100644 --- a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java @@ -4,38 +4,40 @@ import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE; import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK; -import java.io.File; import java.util.HashSet; import java.util.Set; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ProposalService; -import org.tron.core.db.Manager; import org.tron.core.utils.ProposalUtil.ProposalType; import org.tron.protos.Protocol.Proposal; @Slf4j -public class ProposalServiceTest { +public class ProposalServiceTest extends BaseTest { - private static TronApplicationContext context; - private static Manager manager; - private static String dbPath = "output_proposal_test"; + private static boolean init; @BeforeClass public static void init() { + dbPath = "output_proposal_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - manager = context.getBean(Manager.class); - manager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); + + } + + @Before + public void before() { + if (init) { + return; + } + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); + init = true; } @Test @@ -47,12 +49,12 @@ public void test() { Proposal proposal = Proposal.newBuilder().putParameters(1, 1).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); - boolean result = ProposalService.process(manager, proposalCapsule); + boolean result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); // proposal = Proposal.newBuilder().putParameters(1000, 1).build(); proposalCapsule = new ProposalCapsule(proposal); - result = ProposalService.process(manager, proposalCapsule); + result = ProposalService.process(dbManager, proposalCapsule); Assert.assertFalse(result); // for (ProposalType proposalType : ProposalType.values()) { @@ -62,57 +64,47 @@ public void test() { proposal = Proposal.newBuilder().putParameters(proposalType.getCode(), 1).build(); } proposalCapsule = new ProposalCapsule(proposal); - result = ProposalService.process(manager, proposalCapsule); + result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); } } @Test public void testUpdateEnergyFee() { - String preHistory = manager.getDynamicPropertiesStore().getEnergyPriceHistory(); + String preHistory = dbManager.getDynamicPropertiesStore().getEnergyPriceHistory(); long newPrice = 500; Proposal proposal = Proposal.newBuilder().putParameters(ENERGY_FEE.getCode(), newPrice).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); - boolean result = ProposalService.process(manager, proposalCapsule); + boolean result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); - long currentPrice = manager.getDynamicPropertiesStore().getEnergyFee(); + long currentPrice = dbManager.getDynamicPropertiesStore().getEnergyFee(); Assert.assertEquals(currentPrice, newPrice); - String currentHistory = manager.getDynamicPropertiesStore().getEnergyPriceHistory(); + String currentHistory = dbManager.getDynamicPropertiesStore().getEnergyPriceHistory(); Assert.assertEquals(preHistory + "," + proposalCapsule.getExpirationTime() + ":" + newPrice, currentHistory); } @Test public void testUpdateTransactionFee() { - String preHistory = manager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + String preHistory = dbManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); long newPrice = 1500; Proposal proposal = Proposal.newBuilder().putParameters(TRANSACTION_FEE.getCode(), newPrice).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); proposalCapsule.setExpirationTime(1627279200000L); - boolean result = ProposalService.process(manager, proposalCapsule); + boolean result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); - long currentPrice = manager.getDynamicPropertiesStore().getTransactionFee(); + long currentPrice = dbManager.getDynamicPropertiesStore().getTransactionFee(); Assert.assertEquals(currentPrice, newPrice); String expResult = preHistory + "," + proposalCapsule.getExpirationTime() + ":" + newPrice; - String currentHistory = manager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + String currentHistory = dbManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); Assert.assertEquals(expResult, currentHistory); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/WalletApiTest.java b/framework/src/test/java/org/tron/core/services/WalletApiTest.java new file mode 100644 index 00000000000..3e8316666e6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -0,0 +1,61 @@ +package org.tron.core.services; + +import io.grpc.ManagedChannelBuilder; +import java.io.File; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.api.WalletGrpc; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.client.Configuration; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; + + +@Slf4j +public class WalletApiTest { + + private static TronApplicationContext context; + private static String dbPath = "output_wallet_api_test"; + private String fullnode = Configuration.getByPath("testng.conf") + .getStringList("fullnode.ip.list").get(0); + private RpcApiService rpcApiService; + private Application appT; + + @Before + public void init() { + Args.setParam(new String[]{ "-d", dbPath, "--p2p-disable", "true"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + rpcApiService = context.getBean(RpcApiService.class); + appT.addService(rpcApiService); + appT.initServices(Args.getInstance()); + appT.startServices(); + appT.startup(); + } + + @Test + public void listNodesTest() { + WalletGrpc.WalletBlockingStub walletStub = WalletGrpc + .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode) + .usePlaintext() + .build()); + Assert.assertTrue(walletStub.listNodes(EmptyMessage.getDefaultInstance()) + .getNodesList().size() == 0); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java index 4a288b4402c..46449aab9c4 100644 --- a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java @@ -1,60 +1,55 @@ package org.tron.core.services.filter; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.Resource; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.tron.common.BaseTest; import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.parameter.CommonParameter; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; import org.tron.core.services.interfaceOnSolidity.http.solidity.HttpApiOnSolidityService; -public class HttpApiAccessFilterTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); - - private static TronApplicationContext context; - private static Application appTest; - private static CloseableHttpClient httpClient = HttpClients.createDefault(); - private static String dbPath = "output_http_api_access_filter_test"; +public class HttpApiAccessFilterTest extends BaseTest { + + @Resource + private Application appTest; + @Resource + private FullNodeHttpApiService httpApiService; + @Resource + private HttpApiOnSolidityService httpApiOnSolidityService; + @Resource + private HttpApiOnPBFTService httpApiOnPBFTService; + @Resource + private HttpApiAccessFilter httpApiAccessFilter; + private static final CloseableHttpClient httpClient = HttpClients.createDefault(); + + static { + dbPath = "output_http_api_access_filter_test"; + Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); + } /** * init dependencies. */ - @BeforeClass - public static void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); - context = new TronApplicationContext(DefaultConfig.class); - appTest = ApplicationFactory.create(context); - - FullNodeHttpApiService httpApiService = context - .getBean(FullNodeHttpApiService.class); - HttpApiOnSolidityService httpApiOnSolidityService = context - .getBean(HttpApiOnSolidityService.class); - HttpApiOnPBFTService httpApiOnPBFTService = context - .getBean(HttpApiOnPBFTService.class); - + @Before + public void init() { appTest.addService(httpApiService); appTest.addService(httpApiOnSolidityService); appTest.addService(httpApiOnPBFTService); @@ -63,22 +58,6 @@ public static void init() { appTest.startup(); } - /** - * destroy the context. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testHttpFilter() { List disabledApiList = new ArrayList<>(); @@ -113,7 +92,7 @@ public void testHttpFilter() { response); Args.getInstance().setDisabledApiList(emptyList); - int statusCode = getReuqestCode(url); + int statusCode = getRequestCode(url); Assert.assertEquals(HttpStatus.SC_OK, statusCode); } } @@ -122,12 +101,12 @@ public void testHttpFilter() { private String sendGetRequest(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); @@ -139,10 +118,10 @@ private String sendGetRequest(String url) { return null; } - private int getReuqestCode(String url) { + private int getRequestCode(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); @@ -153,4 +132,31 @@ private int getReuqestCode(String url) { return 0; } + + @Test + public void testIsDisabled() throws Exception { + List list = new ArrayList<>(); + list.add("getnowblock"); + CommonParameter.getInstance().setDisabledApiList(list); + Method privateMethod = httpApiAccessFilter.getClass() + .getDeclaredMethod("isDisabled", String.class); + privateMethod.setAccessible(true); + + String url = "/wallet/getnowblock"; + boolean f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertTrue(f); + + url = "/wallet/a/../b/../getnowblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertTrue(f); + + url = "/wallet/a/b/../getnowblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertFalse(f); + + url = "/wallet/getblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertFalse(f); + } + } diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java index 5e5d7d807ae..4ee8fd051d0 100644 --- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java @@ -4,15 +4,15 @@ import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; import java.io.File; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; + import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.DatabaseGrpc; import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; @@ -20,6 +20,7 @@ import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; @@ -28,24 +29,22 @@ import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; +@Slf4j public class LiteFnQueryGrpcInterceptorTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private TronApplicationContext context; private ManagedChannel channelFull = null; private ManagedChannel channelpBFT = null; private WalletGrpc.WalletBlockingStub blockingStubFull = null; private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubpBFT = null; - private DatabaseGrpc.DatabaseBlockingStub databaseBlockingStub = null; private RpcApiService rpcApiService; private RpcApiServiceOnSolidity rpcApiServiceOnSolidity; private RpcApiServiceOnPBFT rpcApiServiceOnPBFT; private Application appTest; private ChainBaseManager chainBaseManager; - private String dbPath = "output_grpc_filter_test"; + private String dbPath = "output_grpc_interceptor_test"; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -56,22 +55,24 @@ public class LiteFnQueryGrpcInterceptorTest { @Before public void init() { Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort()); String fullnode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), Args.getInstance().getRpcPort()); String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), Args.getInstance().getRpcOnPBFTPort()); channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build(); channelpBFT = ManagedChannelBuilder.forTarget(pBFTNode) - .usePlaintext(true) + .usePlaintext() .build(); context = new TronApplicationContext(DefaultConfig.class); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull); blockingStubpBFT = WalletSolidityGrpc.newBlockingStub(channelpBFT); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull); - databaseBlockingStub = DatabaseGrpc.newBlockingStub(channelFull); rpcApiService = context.getBean(RpcApiService.class); rpcApiServiceOnSolidity = context.getBean(RpcApiServiceOnSolidity.class); rpcApiServiceOnPBFT = context.getBean(RpcApiServiceOnPBFT.class); @@ -89,7 +90,13 @@ public void init() { * destroy the context. */ @After - public void destroy() { + public void destroy() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + if (channelpBFT != null) { + channelpBFT.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } Args.clearParam(); appTest.shutdownServices(); appTest.shutdown(); diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java index b63ebc9caed..5c4b955667f 100644 --- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java @@ -1,66 +1,57 @@ package org.tron.core.services.filter; +import static org.tron.core.ChainBaseManager.NodeType.FULL; +import static org.tron.core.ChainBaseManager.NodeType.LITE; + import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.tron.common.BaseTest; import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; import org.tron.core.services.interfaceOnSolidity.http.solidity.HttpApiOnSolidityService; -public class LiteFnQueryHttpFilterTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); +@Slf4j +public class LiteFnQueryHttpFilterTest extends BaseTest { - private TronApplicationContext context; - private String ip = "127.0.0.1"; + private final String ip = "127.0.0.1"; private int fullHttpPort; + @Resource private Application appTest; - private CloseableHttpClient httpClient = HttpClients.createDefault(); + @Resource + private FullNodeHttpApiService httpApiService; + @Resource + private HttpApiOnSolidityService httpApiOnSolidityService; + @Resource + private HttpApiOnPBFTService httpApiOnPBFTService; + private final CloseableHttpClient httpClient = HttpClients.createDefault(); - private String dbPath = "output_http_filter_test"; - - private ChainBaseManager chainBaseManager; + static { + dbPath = "output_http_filter_test"; + Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); + } /** * init dependencies. */ @Before public void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); - context = new TronApplicationContext(DefaultConfig.class); - appTest = ApplicationFactory.create(context); - FullNodeHttpApiService httpApiService = context - .getBean(FullNodeHttpApiService.class); - HttpApiOnSolidityService httpApiOnSolidityService = context - .getBean(HttpApiOnSolidityService.class); - HttpApiOnPBFTService httpApiOnPBFTService = context - .getBean(HttpApiOnPBFTService.class); - chainBaseManager = context.getBean(ChainBaseManager.class); appTest.addService(httpApiService); appTest.addService(httpApiOnSolidityService); appTest.addService(httpApiOnPBFTService); @@ -69,22 +60,6 @@ public void init() { appTest.startup(); } - /** - * destroy the context. - */ - @After - public void destroy() { - Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testHttpFilter() { Set urlPathSets = LiteFnQueryHttpFilter.getFilterPaths(); @@ -98,21 +73,20 @@ public void testHttpFilter() { } String url = String.format("http://%s:%d%s", ip, fullHttpPort, urlPath); // test lite fullnode with history query closed - chainBaseManager.setNodeType(ChainBaseManager.NodeType.LITE); + chainBaseManager.setNodeType(LITE); Args.getInstance().setOpenHistoryQueryWhenLiteFN(false); String response = sendGetRequest(url); - Assert.assertEquals("this API is closed because this node is a lite fullnode", - response); + logger.info("response:{}", response); // test lite fullnode with history query opened - chainBaseManager.setNodeType(ChainBaseManager.NodeType.FULL); + chainBaseManager.setNodeType(FULL); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", response); // test normal fullnode - chainBaseManager.setNodeType(ChainBaseManager.NodeType.FULL); + chainBaseManager.setNodeType(FULL); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", @@ -124,12 +98,12 @@ public void testHttpFilter() { private String sendGetRequest(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); @@ -149,7 +123,7 @@ private String sendPostRequest(String url, String body) throws IOException { HttpResponse response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); diff --git a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java index c3ef7265f65..edd15fc19de 100644 --- a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java @@ -3,18 +3,19 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; +import io.grpc.stub.ServerCallStreamObserver; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; @@ -22,6 +23,7 @@ import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -29,10 +31,9 @@ import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; +@Slf4j public class RpcApiAccessInterceptorTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private static TronApplicationContext context; private static WalletGrpc.WalletBlockingStub blockingStubFull = null; @@ -40,7 +41,7 @@ public class RpcApiAccessInterceptorTest { private static WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPBFT = null; private static Application appTest; - private static String dbPath = "output_rpc_api_access_filter_test"; + private static String dbPath = "output_rpc_api_access_interceptor_test"; @Rule public ExpectedException thrown = ExpectedException.none(); @@ -51,6 +52,9 @@ public class RpcApiAccessInterceptorTest { @BeforeClass public static void init() { Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort()); String fullNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), Args.getInstance().getRpcPort()); String solidityNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), @@ -117,6 +121,106 @@ public void testAccessDisabledFullNode() { blockingStubFull.getBlockByNum(message); } + @Test + public void testRpcApiService() { + RpcApiService rpcApiService = context.getBean(RpcApiService.class); + ServerCallStreamObserverTest serverCallStreamObserverTest = new ServerCallStreamObserverTest(); + rpcApiService.getBlockCommon(GrpcAPI.BlockReq.getDefaultInstance(), + serverCallStreamObserverTest); + Assert.assertTrue("Get block Common failed!", serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBrokerageInfoCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get brokerage info Common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBurnTrxCommon(GrpcAPI.EmptyMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get burn trx common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getPendingSizeCommon(GrpcAPI.EmptyMessage.getDefaultInstance(), + serverCallStreamObserverTest); + Assert.assertTrue("Get pending size common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getRewardInfoCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get reward info common failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionCountByBlockNumCommon( + GrpcAPI.NumberMessage.newBuilder().getDefaultInstanceForType(), + serverCallStreamObserverTest); + Assert.assertTrue("Get transaction count by block num failed!", + serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionFromPendingCommon(GrpcAPI.BytesMessage.newBuilder().build(), + serverCallStreamObserverTest); + Assert.assertTrue("Get transaction from pending failed!", + serverCallStreamObserverTest.isReady() == false); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionListFromPendingCommon(GrpcAPI.EmptyMessage.newBuilder() + .getDefaultInstanceForType(), serverCallStreamObserverTest); + Assert.assertTrue("Get transaction list from pending failed!", + serverCallStreamObserverTest.isReady()); + } + + + class ServerCallStreamObserverTest extends ServerCallStreamObserver { + + Object ret; + + @Override + public boolean isCancelled() { + ret = null; + return true; + } + + @Override + public void setOnCancelHandler(Runnable onCancelHandler) { + } + + @Override + public void setCompression(String compression) { + } + + @Override + public boolean isReady() { + return Objects.nonNull(ret); + } + + @Override + public void setOnReadyHandler(Runnable onReadyHandler) { + } + + @Override + public void disableAutoInboundFlowControl() { + } + + @Override + public void request(int count) { + } + + @Override + public void setMessageCompression(boolean enable) { + } + + @Override + public void onNext(Object value) { + ret = value; + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onCompleted() { + } + } + + @Test public void testAccessDisabledSolidityNode() { List disabledApiList = new ArrayList<>(); diff --git a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java index 8b255a0f395..24ec969c08b 100644 --- a/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/BroadcastServletTest.java @@ -57,10 +57,9 @@ public static void init() { /** * set up. * - * @throws InterruptedException . */ @Before - public void setUp() throws InterruptedException { + public void setUp() { broadcastServlet = new BroadcastServlet(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); @@ -82,7 +81,7 @@ public void tearDown() { } @Test - public void testDoPost() throws IOException { + public void doPostTest() throws IOException { URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); @@ -115,7 +114,7 @@ public void testDoPost() throws IOException { + "eapis.com/protocol.TransferContract\"},\"type\":\"TransferCon" + "tract\"}],\"ref_block_bytes\":\"267e\",\"ref_block_hash\":\"9a447d222e8" + "de9f2\",\"expiration\":1530893064000,\"timestamp\":1530893006233}}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -140,14 +139,15 @@ public void testDoPost() throws IOException { while ((line = in.readLine()) != null) { result.append(line).append("\n"); } + Assert.assertNotNull(result); in.close(); writer.flush(); FileInputStream fileInputStream = new FileInputStream("temp.txt"); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } diff --git a/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java b/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java new file mode 100644 index 00000000000..dfd4c569e3e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java @@ -0,0 +1,534 @@ +package org.tron.core.services.http; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +@Slf4j +public class HttpServletTest { + private AccountPermissionUpdateServlet accountPermissionUpdateServlet; + private BroadcastHexServlet broadcastHexServlet; + private BroadcastServlet broadcastServlet; + private ClearABIServlet clearABIServlet; + private CreateAccountServlet createAccountServlet; + private CreateAssetIssueServlet createAssetIssueServlet; + private CreateCommonTransactionServlet createCommonTransactionServlet; + private CreateShieldedContractParametersServlet createShieldedContractParametersServlet; + private CreateShieldedContractParametersWithoutAskServlet + createShieldedContractParametersWithoutAskServlet; + private CreateShieldedTransactionServlet createShieldedTransactionServlet; + private CreateShieldedTransactionWithoutSpendAuthSigServlet + createShieldedTransactionWithoutSpendAuthSigServlet; + private CreateShieldNullifierServlet createShieldNullifierServlet; + private CreateSpendAuthSigServlet createSpendAuthSigServlet; + private CreateWitnessServlet createWitnessServlet; + private DelegateResourceServlet delegateResourceServlet; + private DeployContractServlet deployContractServlet; + private EstimateEnergyServlet estimateEnergyServlet; + private ExchangeCreateServlet exchangeCreateServlet; + private ExchangeInjectServlet exchangeInjectServlet; + private ExchangeTransactionServlet exchangeTransactionServlet; + private ExchangeWithdrawServlet exchangeWithdrawServlet; + private FreezeBalanceServlet freezeBalanceServlet; + private FreezeBalanceV2Servlet freezeBalanceV2Servlet; + private GetAccountBalanceServlet getAccountBalanceServlet; + private GetAccountByIdServlet getAccountByIdServlet; + private GetAccountNetServlet getAccountNetServlet; + private GetAccountResourceServlet getAccountResourceServlet; + private GetAccountServlet getAccountServlet; + private GetAkFromAskServlet getAkFromAskServlet; + private GetAssetIssueByAccountServlet getAssetIssueByAccountServlet; + private GetAssetIssueByIdServlet getAssetIssueByIdServlet; + private GetAssetIssueByNameServlet getAssetIssueByNameServlet; + private GetAssetIssueListByNameServlet getAssetIssueListByNameServlet; + private GetAssetIssueListServlet getAssetIssueListServlet; + private GetAvailableUnfreezeCountServlet getAvailableUnfreezeCountServlet; + private GetBandwidthPricesServlet getBandwidthPricesServlet; + private GetBlockBalanceServlet getBlockBalanceServlet; + private GetBlockByIdServlet getBlockByIdServlet; + private GetBlockByLatestNumServlet getBlockByLatestNumServlet; + private GetBlockByLimitNextServlet getBlockByLimitNextServlet; + private GetBlockByNumServlet getBlockByNumServlet; + private GetBlockServlet getBlockServlet; + private GetBrokerageServlet getBrokerageServlet; + private GetBurnTrxServlet getBurnTrxServlet; + private GetCanDelegatedMaxSizeServlet getCanDelegatedMaxSizeServlet; + private GetCanWithdrawUnfreezeAmountServlet getCanWithdrawUnfreezeAmountServlet; + private GetChainParametersServlet getChainParametersServlet; + private GetContractInfoServlet getContractInfoServlet; + private GetContractServlet getContractServlet; + private GetDelegatedResourceAccountIndexServlet getDelegatedResourceAccountIndexServlet; + private GetDelegatedResourceAccountIndexV2Servlet getDelegatedResourceAccountIndexV2Servlet; + private GetDelegatedResourceServlet getDelegatedResourceServlet; + private GetDelegatedResourceV2Servlet getDelegatedResourceV2Servlet; + private GetDiversifierServlet getDiversifierServlet; + private GetEnergyPricesServlet getEnergyPricesServlet; + private GetExchangeByIdServlet getExchangeByIdServlet; + private GetExpandedSpendingKeyServlet getExpandedSpendingKeyServlet; + private GetIncomingViewingKeyServlet getIncomingViewingKeyServlet; + private GetMarketOrderByAccountServlet getMarketOrderByAccountServlet; + private GetMarketOrderByIdServlet getMarketOrderByIdServlet; + private GetMarketOrderListByPairServlet getMarketOrderListByPairServlet; + private GetMarketPairListServlet getMarketPairListServlet; + private GetMarketPriceByPairServlet getMarketPriceByPairServlet; + private GetMemoFeePricesServlet getMemoFeePricesServlet; + private GetMerkleTreeVoucherInfoServlet getMerkleTreeVoucherInfoServlet; + private GetNewShieldedAddressServlet getNewShieldedAddressServlet; + private GetNextMaintenanceTimeServlet getNextMaintenanceTimeServlet; + private GetNkFromNskServlet getNkFromNskServlet; + private GetNodeInfoServlet getNodeInfoServlet; + private GetNowBlockServlet getNowBlockServlet; + private GetPaginatedAssetIssueListServlet getPaginatedAssetIssueListServlet; + private GetPaginatedExchangeListServlet getPaginatedExchangeListServlet; + private GetPaginatedProposalListServlet getPaginatedProposalListServlet; + private GetPendingSizeServlet getPendingSizeServlet; + private GetProposalByIdServlet getProposalByIdServlet; + private GetRcmServlet getRcmServlet; + private GetRewardServlet getRewardServlet; + private GetShieldTransactionHashServlet getShieldTransactionHashServlet; + private GetSpendingKeyServlet getSpendingKeyServlet; + private GetTransactionApprovedListServlet getTransactionApprovedListServlet; + private GetTransactionByIdServlet getTransactionByIdServlet; + private GetTransactionCountByBlockNumServlet getTransactionCountByBlockNumServlet; + private GetTransactionFromPendingServlet getTransactionFromPendingServlet; + private GetTransactionInfoByBlockNumServlet getTransactionInfoByBlockNumServlet; + private GetTransactionInfoByIdServlet getTransactionInfoByIdServlet; + private GetTransactionListFromPendingServlet getTransactionListFromPendingServlet; + private GetTransactionReceiptByIdServlet getTransactionReceiptByIdServlet; + private GetTransactionSignWeightServlet getTransactionSignWeightServlet; + private GetTriggerInputForShieldedTRC20ContractServlet + getTriggerInputForShieldedTRC20ContractServlet; + private GetZenPaymentAddressServlet getZenPaymentAddressServlet; + private IsShieldedTRC20ContractNoteSpentServlet isShieldedTRC20ContractNoteSpentServlet; + private IsSpendServlet isSpendServlet; + private ListExchangesServlet listExchangesServlet; + private ListNodesServlet listNodesServlet; + private ListProposalsServlet listProposalsServlet; + private ListWitnessesServlet listWitnessesServlet; + private MarketCancelOrderServlet marketCancelOrderServlet; + private MarketSellAssetServlet marketSellAssetServlet; + private MetricsServlet metricsServlet; + private ParticipateAssetIssueServlet participateAssetIssueServlet; + private ProposalApproveServlet proposalApproveServlet; + private ProposalCreateServlet proposalCreateServlet; + private ProposalDeleteServlet proposalDeleteServlet; + private ScanAndMarkNoteByIvkServlet scanAndMarkNoteByIvkServlet; + private ScanNoteByIvkServlet scanNoteByIvkServlet; + private ScanNoteByOvkServlet scanNoteByOvkServlet; + private ScanShieldedTRC20NotesByIvkServlet scanShieldedTRC20NotesByIvkServlet; + private ScanShieldedTRC20NotesByOvkServlet scanShieldedTRC20NotesByOvkServlet; + private SetAccountIdServlet setAccountIdServlet; + private TotalTransactionServlet totalTransactionServlet; + private TransferAssetServlet transferAssetServlet; + private TransferServlet transferServlet; + private TriggerConstantContractServlet triggerConstantContractServlet; + private TriggerSmartContractServlet triggerSmartContractServlet; + private UnDelegateResourceServlet unDelegateResourceServlet; + private UnFreezeAssetServlet unFreezeAssetServlet; + private UnFreezeBalanceServlet unFreezeBalanceServlet; + private UnFreezeBalanceV2Servlet unFreezeBalanceV2Servlet; + private UpdateAccountServlet updateAccountServlet; + private UpdateAssetServlet updateAssetServlet; + private UpdateBrokerageServlet updateBrokerageServlet; + private UpdateEnergyLimitServlet updateEnergyLimitServlet; + private UpdateSettingServlet updateSettingServlet; + private UpdateWitnessServlet updateWitnessServlet; + private ValidateAddressServlet validateAddressServlet; + private VoteWitnessAccountServlet voteWitnessAccountServlet; + private WithdrawBalanceServlet withdrawBalanceServlet; + private WithdrawExpireUnfreezeServlet withdrawExpireUnfreezeServlet; + private CancelAllUnfreezeV2Servlet cancelAllUnfreezeV2Servlet; + private MockHttpServletRequest request; + private MockHttpServletResponse response; + + @Before + public void setUp() { + accountPermissionUpdateServlet = new AccountPermissionUpdateServlet(); + broadcastHexServlet = new BroadcastHexServlet(); + broadcastServlet = new BroadcastServlet(); + clearABIServlet = new ClearABIServlet(); + createAccountServlet = new CreateAccountServlet(); + createAssetIssueServlet = new CreateAssetIssueServlet(); + createCommonTransactionServlet = new CreateCommonTransactionServlet(); + createShieldedContractParametersServlet = new CreateShieldedContractParametersServlet(); + createShieldedContractParametersWithoutAskServlet = + new CreateShieldedContractParametersWithoutAskServlet(); + createShieldedTransactionServlet = new CreateShieldedTransactionServlet(); + createShieldedTransactionWithoutSpendAuthSigServlet = + new CreateShieldedTransactionWithoutSpendAuthSigServlet(); + createShieldNullifierServlet = new CreateShieldNullifierServlet(); + createSpendAuthSigServlet = new CreateSpendAuthSigServlet(); + createWitnessServlet = new CreateWitnessServlet(); + delegateResourceServlet = new DelegateResourceServlet(); + deployContractServlet = new DeployContractServlet(); + estimateEnergyServlet = new EstimateEnergyServlet(); + exchangeCreateServlet = new ExchangeCreateServlet(); + exchangeInjectServlet = new ExchangeInjectServlet(); + exchangeTransactionServlet = new ExchangeTransactionServlet(); + exchangeWithdrawServlet = new ExchangeWithdrawServlet(); + freezeBalanceServlet = new FreezeBalanceServlet(); + freezeBalanceV2Servlet = new FreezeBalanceV2Servlet(); + getAccountBalanceServlet = new GetAccountBalanceServlet(); + getAccountByIdServlet = new GetAccountByIdServlet(); + getAccountNetServlet = new GetAccountNetServlet(); + getAccountResourceServlet = new GetAccountResourceServlet(); + getAccountServlet = new GetAccountServlet(); + getAkFromAskServlet = new GetAkFromAskServlet(); + getAssetIssueByAccountServlet = new GetAssetIssueByAccountServlet(); + getAssetIssueByIdServlet = new GetAssetIssueByIdServlet(); + getAssetIssueByNameServlet = new GetAssetIssueByNameServlet(); + getAssetIssueListByNameServlet = new GetAssetIssueListByNameServlet(); + getAssetIssueListServlet = new GetAssetIssueListServlet(); + getAvailableUnfreezeCountServlet = new GetAvailableUnfreezeCountServlet(); + getBandwidthPricesServlet = new GetBandwidthPricesServlet(); + getBlockBalanceServlet = new GetBlockBalanceServlet(); + getBlockByIdServlet = new GetBlockByIdServlet(); + getBlockByLatestNumServlet = new GetBlockByLatestNumServlet(); + getBlockByLimitNextServlet = new GetBlockByLimitNextServlet(); + getBlockByNumServlet = new GetBlockByNumServlet(); + getBlockServlet = new GetBlockServlet(); + getBrokerageServlet = new GetBrokerageServlet(); + getBurnTrxServlet = new GetBurnTrxServlet(); + getCanDelegatedMaxSizeServlet = new GetCanDelegatedMaxSizeServlet(); + getCanWithdrawUnfreezeAmountServlet = new GetCanWithdrawUnfreezeAmountServlet(); + getChainParametersServlet = new GetChainParametersServlet(); + getContractInfoServlet = new GetContractInfoServlet(); + getContractServlet = new GetContractServlet(); + getDelegatedResourceAccountIndexServlet = new GetDelegatedResourceAccountIndexServlet(); + getDelegatedResourceAccountIndexV2Servlet = new GetDelegatedResourceAccountIndexV2Servlet(); + getDelegatedResourceServlet = new GetDelegatedResourceServlet(); + getDelegatedResourceV2Servlet = new GetDelegatedResourceV2Servlet(); + getDiversifierServlet = new GetDiversifierServlet(); + getEnergyPricesServlet = new GetEnergyPricesServlet(); + getExchangeByIdServlet = new GetExchangeByIdServlet(); + getExpandedSpendingKeyServlet = new GetExpandedSpendingKeyServlet(); + getIncomingViewingKeyServlet = new GetIncomingViewingKeyServlet(); + getMarketOrderByAccountServlet = new GetMarketOrderByAccountServlet(); + getMarketOrderByIdServlet = new GetMarketOrderByIdServlet(); + getMarketOrderListByPairServlet = new GetMarketOrderListByPairServlet(); + getMarketPairListServlet = new GetMarketPairListServlet(); + getMarketPriceByPairServlet = new GetMarketPriceByPairServlet(); + getMemoFeePricesServlet = new GetMemoFeePricesServlet(); + getMerkleTreeVoucherInfoServlet = new GetMerkleTreeVoucherInfoServlet(); + getNewShieldedAddressServlet = new GetNewShieldedAddressServlet(); + getNextMaintenanceTimeServlet = new GetNextMaintenanceTimeServlet(); + getNkFromNskServlet = new GetNkFromNskServlet(); + getNodeInfoServlet = new GetNodeInfoServlet(); + getNowBlockServlet = new GetNowBlockServlet(); + getPaginatedAssetIssueListServlet = new GetPaginatedAssetIssueListServlet(); + getPaginatedExchangeListServlet = new GetPaginatedExchangeListServlet(); + getPaginatedProposalListServlet = new GetPaginatedProposalListServlet(); + getPendingSizeServlet = new GetPendingSizeServlet(); + getProposalByIdServlet = new GetProposalByIdServlet(); + getRcmServlet = new GetRcmServlet(); + getRewardServlet = new GetRewardServlet(); + getShieldTransactionHashServlet = new GetShieldTransactionHashServlet(); + getSpendingKeyServlet = new GetSpendingKeyServlet(); + getTransactionApprovedListServlet = new GetTransactionApprovedListServlet(); + getTransactionByIdServlet = new GetTransactionByIdServlet(); + getTransactionCountByBlockNumServlet = new GetTransactionCountByBlockNumServlet(); + getTransactionFromPendingServlet = new GetTransactionFromPendingServlet(); + getTransactionInfoByBlockNumServlet = new GetTransactionInfoByBlockNumServlet(); + getTransactionInfoByIdServlet = new GetTransactionInfoByIdServlet(); + getTransactionListFromPendingServlet = new GetTransactionListFromPendingServlet(); + getTransactionReceiptByIdServlet = new GetTransactionReceiptByIdServlet(); + getTransactionSignWeightServlet = new GetTransactionSignWeightServlet(); + getTriggerInputForShieldedTRC20ContractServlet = + new GetTriggerInputForShieldedTRC20ContractServlet(); + getZenPaymentAddressServlet = new GetZenPaymentAddressServlet(); + isShieldedTRC20ContractNoteSpentServlet = new IsShieldedTRC20ContractNoteSpentServlet(); + isSpendServlet = new IsSpendServlet(); + listExchangesServlet = new ListExchangesServlet(); + listNodesServlet = new ListNodesServlet(); + listProposalsServlet = new ListProposalsServlet(); + listWitnessesServlet = new ListWitnessesServlet(); + marketCancelOrderServlet = new MarketCancelOrderServlet(); + marketSellAssetServlet = new MarketSellAssetServlet(); + metricsServlet = new MetricsServlet(); + participateAssetIssueServlet = new ParticipateAssetIssueServlet(); + proposalApproveServlet = new ProposalApproveServlet(); + proposalCreateServlet = new ProposalCreateServlet(); + proposalDeleteServlet = new ProposalDeleteServlet(); + scanAndMarkNoteByIvkServlet = new ScanAndMarkNoteByIvkServlet(); + scanNoteByIvkServlet = new ScanNoteByIvkServlet(); + scanNoteByOvkServlet = new ScanNoteByOvkServlet(); + scanShieldedTRC20NotesByIvkServlet = new ScanShieldedTRC20NotesByIvkServlet(); + scanShieldedTRC20NotesByOvkServlet = new ScanShieldedTRC20NotesByOvkServlet(); + setAccountIdServlet = new SetAccountIdServlet(); + totalTransactionServlet = new TotalTransactionServlet(); + transferAssetServlet = new TransferAssetServlet(); + transferServlet = new TransferServlet(); + triggerConstantContractServlet = new TriggerConstantContractServlet(); + triggerSmartContractServlet = new TriggerSmartContractServlet(); + unDelegateResourceServlet = new UnDelegateResourceServlet(); + unFreezeAssetServlet = new UnFreezeAssetServlet(); + unFreezeBalanceServlet = new UnFreezeBalanceServlet(); + unFreezeBalanceV2Servlet = new UnFreezeBalanceV2Servlet(); + updateAccountServlet = new UpdateAccountServlet(); + updateAssetServlet = new UpdateAssetServlet(); + updateBrokerageServlet = new UpdateBrokerageServlet(); + updateEnergyLimitServlet = new UpdateEnergyLimitServlet(); + updateSettingServlet = new UpdateSettingServlet(); + updateWitnessServlet = new UpdateWitnessServlet(); + validateAddressServlet = new ValidateAddressServlet(); + voteWitnessAccountServlet = new VoteWitnessAccountServlet(); + withdrawBalanceServlet = new WithdrawBalanceServlet(); + withdrawExpireUnfreezeServlet = new WithdrawExpireUnfreezeServlet(); + cancelAllUnfreezeV2Servlet = new CancelAllUnfreezeV2Servlet(); + request = new MockHttpServletRequest(); + request.setCharacterEncoding("UTF-8"); + response = new MockHttpServletResponse(); + } + + @Test + public void doGetTest() { + accountPermissionUpdateServlet.doGet(request, response); + clearABIServlet.doGet(request, response); + createAssetIssueServlet.doGet(request, response); + createShieldedContractParametersServlet.doGet(request, response); + createShieldedContractParametersWithoutAskServlet.doGet(request, response); + createShieldedTransactionServlet.doGet(request, response); + createShieldedTransactionWithoutSpendAuthSigServlet.doGet(request, response); + createShieldNullifierServlet.doGet(request, response); + createSpendAuthSigServlet.doGet(request, response); + createWitnessServlet.doGet(request, response); + deployContractServlet.doGet(request, response); + estimateEnergyServlet.doGet(request, response); + getAccountByIdServlet.doGet(request, response); + getAccountNetServlet.doGet(request, response); + getAccountResourceServlet.doGet(request, response); + getAccountServlet.doGet(request, response); + getAkFromAskServlet.doGet(request, response); + getAssetIssueByAccountServlet.doGet(request, response); + getAssetIssueByIdServlet.doGet(request, response); + getAssetIssueByNameServlet.doGet(request, response); + getAssetIssueListByNameServlet.doGet(request, response); + getAssetIssueListServlet.doGet(request, response); + getAvailableUnfreezeCountServlet.doGet(request, response); + getBandwidthPricesServlet.doGet(request, response); + getBlockByIdServlet.doGet(request, response); + getBlockByLatestNumServlet.doGet(request, response); + getBlockByLimitNextServlet.doGet(request, response); + getBlockByNumServlet.doGet(request, response); + getBlockServlet.doGet(request, response); + getBrokerageServlet.doGet(request, response); + getBurnTrxServlet.doGet(request, response); + getCanDelegatedMaxSizeServlet.doGet(request, response); + getCanWithdrawUnfreezeAmountServlet.doGet(request, response); + getChainParametersServlet.doGet(request, response); + getContractInfoServlet.doGet(request, response); + getContractServlet.doGet(request, response); + getDelegatedResourceAccountIndexServlet.doGet(request, response); + getDelegatedResourceAccountIndexV2Servlet.doGet(request, response); + getDelegatedResourceServlet.doGet(request, response); + getDelegatedResourceV2Servlet.doGet(request, response); + getDiversifierServlet.doGet(request, response); + getEnergyPricesServlet.doGet(request, response); + getExchangeByIdServlet.doGet(request, response); + getExpandedSpendingKeyServlet.doGet(request, response); + getIncomingViewingKeyServlet.doGet(request, response); + getMarketOrderByAccountServlet.doGet(request, response); + getMarketOrderByIdServlet.doGet(request, response); + getMarketOrderListByPairServlet.doGet(request, response); + getMarketPairListServlet.doGet(request, response); + getMarketPriceByPairServlet.doGet(request, response); + getMemoFeePricesServlet.doGet(request, response); + getMerkleTreeVoucherInfoServlet.doGet(request, response); + getNewShieldedAddressServlet.doGet(request, response); + getNextMaintenanceTimeServlet.doGet(request, response); + getNkFromNskServlet.doGet(request, response); + getNodeInfoServlet.doGet(request, response); + getNowBlockServlet.doGet(request, response); + getPaginatedAssetIssueListServlet.doGet(request, response); + getPaginatedExchangeListServlet.doGet(request, response); + getPaginatedProposalListServlet.doGet(request, response); + getPendingSizeServlet.doGet(request, response); + getProposalByIdServlet.doGet(request, response); + getRcmServlet.doGet(request, response); + getRewardServlet.doGet(request, response); + getShieldTransactionHashServlet.doGet(request, response); + getSpendingKeyServlet.doGet(request, response); + getTransactionApprovedListServlet.doGet(request, response); + getTransactionByIdServlet.doGet(request, response); + getTransactionCountByBlockNumServlet.doGet(request, response); + getTransactionFromPendingServlet.doGet(request, response); + getTransactionInfoByBlockNumServlet.doGet(request, response); + getTransactionInfoByIdServlet.doGet(request, response); + getTransactionListFromPendingServlet.doGet(request, response); + getTransactionReceiptByIdServlet.doGet(request, response); + getTransactionSignWeightServlet.doGet(request, response); + getTriggerInputForShieldedTRC20ContractServlet.doGet(request, response); + getZenPaymentAddressServlet.doGet(request, response); + isShieldedTRC20ContractNoteSpentServlet.doGet(request, response); + isSpendServlet.doGet(request, response); + listExchangesServlet.doGet(request, response); + listNodesServlet.doGet(request, response); + listProposalsServlet.doGet(request, response); + listWitnessesServlet.doGet(request, response); + marketCancelOrderServlet.doGet(request, response); + marketSellAssetServlet.doGet(request, response); + metricsServlet.doGet(request, response); + participateAssetIssueServlet.doGet(request, response); + proposalApproveServlet.doGet(request, response); + proposalCreateServlet.doGet(request, response); + proposalDeleteServlet.doGet(request, response); + scanAndMarkNoteByIvkServlet.doGet(request, response); + scanNoteByIvkServlet.doGet(request, response); + scanNoteByOvkServlet.doGet(request, response); + scanShieldedTRC20NotesByIvkServlet.doGet(request, response); + scanShieldedTRC20NotesByOvkServlet.doGet(request, response); + setAccountIdServlet.doGet(request, response); + totalTransactionServlet.doGet(request, response); + transferAssetServlet.doGet(request, response); + transferServlet.doGet(request, response); + triggerConstantContractServlet.doGet(request, response); + triggerSmartContractServlet.doGet(request, response); + unDelegateResourceServlet.doGet(request, response); + unFreezeAssetServlet.doGet(request, response); + unFreezeBalanceServlet.doGet(request, response); + unFreezeBalanceV2Servlet.doGet(request, response); + updateAccountServlet.doGet(request, response); + updateAssetServlet.doGet(request, response); + updateEnergyLimitServlet.doGet(request, response); + updateSettingServlet.doGet(request, response); + updateWitnessServlet.doGet(request, response); + validateAddressServlet.doGet(request, response); + voteWitnessAccountServlet.doGet(request, response); + withdrawBalanceServlet.doGet(request, response); + withdrawExpireUnfreezeServlet.doGet(request, response); + } + + + @Test + public void doPostTest() { + request.addParameter("owner_address", "TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g"); + accountPermissionUpdateServlet.doPost(request, response); + broadcastHexServlet.doPost(request, response); + broadcastServlet.doPost(request, response); + clearABIServlet.doPost(request, response); + createAccountServlet.doPost(request, response); + createAssetIssueServlet.doPost(request, response); + createCommonTransactionServlet.doPost(request, response); + createShieldedContractParametersServlet.doPost(request, response); + createShieldedContractParametersWithoutAskServlet.doPost(request, response); + createShieldedTransactionServlet.doPost(request, response); + createShieldedTransactionWithoutSpendAuthSigServlet.doPost(request, response); + createShieldNullifierServlet.doPost(request, response); + createSpendAuthSigServlet.doPost(request, response); + createWitnessServlet.doPost(request, response); + delegateResourceServlet.doPost(request, response); + deployContractServlet.doPost(request, response); + exchangeCreateServlet.doPost(request, response); + exchangeInjectServlet.doPost(request, response); + exchangeTransactionServlet.doPost(request, response); + exchangeWithdrawServlet.doPost(request, response); + freezeBalanceServlet.doPost(request, response); + freezeBalanceV2Servlet.doPost(request, response); + getAccountBalanceServlet.doPost(request, response); + getAccountByIdServlet.doPost(request, response); + getAccountNetServlet.doPost(request, response); + getAccountResourceServlet.doPost(request, response); + getAccountServlet.doPost(request, response); + getAkFromAskServlet.doPost(request, response); + getAssetIssueByAccountServlet.doPost(request, response); + getAssetIssueByIdServlet.doPost(request, response); + getAssetIssueByNameServlet.doPost(request, response); + getAssetIssueListByNameServlet.doPost(request, response); + getAssetIssueListServlet.doPost(request, response); + getAvailableUnfreezeCountServlet.doPost(request, response); + getBandwidthPricesServlet.doPost(request, response); + getBlockBalanceServlet.doPost(request, response); + getBlockByIdServlet.doPost(request, response); + getBlockByLatestNumServlet.doPost(request, response); + getBlockByLimitNextServlet.doPost(request, response); + getBlockByNumServlet.doPost(request, response); + getBlockServlet.doPost(request, response); + getBrokerageServlet.doPost(request, response); + getBurnTrxServlet.doPost(request, response); + getCanDelegatedMaxSizeServlet.doPost(request, response); + getCanWithdrawUnfreezeAmountServlet.doPost(request, response); + getChainParametersServlet.doPost(request, response); + getContractInfoServlet.doPost(request, response); + getContractServlet.doPost(request, response); + getDelegatedResourceAccountIndexServlet.doPost(request, response); + getDelegatedResourceAccountIndexV2Servlet.doPost(request, response); + getDelegatedResourceServlet.doPost(request, response); + getDelegatedResourceV2Servlet.doPost(request, response); + getDiversifierServlet.doPost(request, response); + getEnergyPricesServlet.doPost(request, response); + getExchangeByIdServlet.doPost(request, response); + getExpandedSpendingKeyServlet.doPost(request, response); + getIncomingViewingKeyServlet.doPost(request, response); + getMarketOrderByAccountServlet.doPost(request, response); + getMarketOrderByIdServlet.doPost(request, response); + getMarketOrderListByPairServlet.doPost(request, response); + getMarketPairListServlet.doPost(request, response); + getMarketPriceByPairServlet.doPost(request, response); + getMemoFeePricesServlet.doPost(request, response); + getMerkleTreeVoucherInfoServlet.doPost(request, response); + getNewShieldedAddressServlet.doPost(request, response); + getNextMaintenanceTimeServlet.doPost(request, response); + getNkFromNskServlet.doPost(request, response); + getNodeInfoServlet.doPost(request, response); + getNowBlockServlet.doPost(request, response); + getPaginatedAssetIssueListServlet.doPost(request, response); + getPaginatedExchangeListServlet.doPost(request, response); + getPaginatedProposalListServlet.doPost(request, response); + getPendingSizeServlet.doPost(request, response); + getProposalByIdServlet.doPost(request, response); + getRcmServlet.doPost(request, response); + getRewardServlet.doPost(request, response); + getShieldTransactionHashServlet.doPost(request, response); + getSpendingKeyServlet.doPost(request, response); + getTransactionApprovedListServlet.doPost(request, response); + getTransactionByIdServlet.doPost(request, response); + getTransactionCountByBlockNumServlet.doPost(request, response); + getTransactionFromPendingServlet.doPost(request, response); + getTransactionInfoByBlockNumServlet.doPost(request, response); + getTransactionInfoByIdServlet.doPost(request, response); + getTransactionListFromPendingServlet.doPost(request, response); + getTransactionReceiptByIdServlet.doPost(request, response); + getTransactionSignWeightServlet.doPost(request, response); + getTriggerInputForShieldedTRC20ContractServlet.doPost(request, response); + getZenPaymentAddressServlet.doPost(request, response); + isShieldedTRC20ContractNoteSpentServlet.doPost(request, response); + isSpendServlet.doPost(request, response); + listExchangesServlet.doPost(request, response); + listNodesServlet.doPost(request, response); + listProposalsServlet.doPost(request, response); + listWitnessesServlet.doPost(request, response); + marketCancelOrderServlet.doPost(request, response); + marketSellAssetServlet.doPost(request, response); + participateAssetIssueServlet.doPost(request, response); + proposalApproveServlet.doPost(request, response); + proposalCreateServlet.doPost(request, response); + proposalDeleteServlet.doPost(request, response); + scanAndMarkNoteByIvkServlet.doPost(request, response); + scanNoteByIvkServlet.doPost(request, response); + scanNoteByOvkServlet.doPost(request, response); + scanShieldedTRC20NotesByIvkServlet.doPost(request, response); + scanShieldedTRC20NotesByOvkServlet.doPost(request, response); + setAccountIdServlet.doPost(request, response); + totalTransactionServlet.doPost(request, response); + transferAssetServlet.doPost(request, response); + transferServlet.doPost(request, response); + unDelegateResourceServlet.doPost(request, response); + unFreezeAssetServlet.doPost(request, response); + unFreezeBalanceServlet.doPost(request, response); + unFreezeBalanceV2Servlet.doPost(request, response); + updateAccountServlet.doPost(request, response); + updateAssetServlet.doPost(request, response); + updateBrokerageServlet.doPost(request, response); + updateEnergyLimitServlet.doPost(request, response); + updateSettingServlet.doPost(request, response); + updateWitnessServlet.doPost(request, response); + validateAddressServlet.doPost(request, response); + voteWitnessAccountServlet.doPost(request, response); + withdrawBalanceServlet.doPost(request, response); + withdrawExpireUnfreezeServlet.doPost(request, response); + cancelAllUnfreezeV2Servlet.doPost(request, response); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java b/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java new file mode 100644 index 00000000000..8adae9b8c3d --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java @@ -0,0 +1,102 @@ +package org.tron.core.services.http; + +import com.google.gson.JsonObject; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.tron.common.BaseTest; +import org.tron.common.application.Application; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.client.Configuration; +import org.tron.common.utils.client.utils.HttpMethed; +import org.tron.core.Constant; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; +import org.tron.protos.contract.SmartContractOuterClass; + +@Slf4j +public class TriggerSmartContractServletTest extends BaseTest { + private static final String httpNode = Configuration.getByPath("testng.conf") + .getStringList("httpnode.ip.list") + .get(0); + private static final byte[] ownerAddr = Hex.decode("410000000000000000000000000000000000000000"); + private static final byte[] contractAddr = Hex.decode( + "41000000000000000000000000000000000000dEaD"); + + @Resource + private FullNodeHttpApiService httpApiService; + @Resource + private Application appT; + + @BeforeClass + public static void init() throws Exception { + dbPath = "output_" + TriggerSmartContractServletTest.class.getName(); + Args.setParam( + new String[]{"--output-directory", dbPath, "--debug", "--witness"}, Constant.TEST_CONF); + Args.getInstance().needSyncCheck = false; + + // build app context + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + beanFactory.setAllowCircularReferences(false); + } + + @Before + public void before() { + appT.addService(httpApiService); + + // start services + appT.initServices(Args.getInstance()); + appT.startServices(); + appT.startup(); + + // create contract for testing + Repository rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(contractAddr, Protocol.AccountType.Contract); + rootRepository.createContract(contractAddr, new ContractCapsule( + SmartContractOuterClass.SmartContract.newBuilder().build())); + rootRepository.saveCode(contractAddr, Hex.decode( + "608060405260043610601c5760003560e01c8063f8a8fd6d146021575b600080fd5b60276029565b00" + + "5b3373ffffffffffffffffffffffffffffffffffffffff166108fc34908115029060405160006040518" + + "0830381858888f19350505050158015606e573d6000803e3d6000fd5b5056fea2646970667358221220" + + "45fe2c565cf16b27bb8cbafbe251a850a0bb5cd8806a186dbda12d57685ced6f64736f6c63430008120" + + "033")); + rootRepository.commit(); + } + + + @Test + public void testNormalCall() { + HttpMethed.waitToProduceOneBlock(httpNode); + JsonObject parameter = new JsonObject(); + parameter.addProperty("owner_address", ByteArray.toHexString(ownerAddr)); + parameter.addProperty("contract_address", ByteArray.toHexString(contractAddr)); + parameter.addProperty("function_selector", "test()"); + HttpResponse triggersmartcontract1 = invokeToLocal("triggersmartcontract", parameter); + HttpResponse triggersmartcontract2 = invokeToLocal("triggerconstantcontract", parameter); + HttpResponse triggersmartcontract3 = invokeToLocal("estimateenergy", parameter); + Assert.assertNotNull(triggersmartcontract1); + Assert.assertNotNull(triggersmartcontract2); + Assert.assertNotNull(triggersmartcontract3); + } + + public static HttpResponse invokeToLocal( + String method, JsonObject parameter) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/" + method; + return HttpMethed.createConnect(requestUrl, parameter); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/UtilTest.java b/framework/src/test/java/org/tron/core/services/http/UtilTest.java index fed314ba44e..1f698796ba7 100644 --- a/framework/src/test/java/org/tron/core/services/http/UtilTest.java +++ b/framework/src/test/java/org/tron/core/services/http/UtilTest.java @@ -1,44 +1,27 @@ package org.tron.core.services.http; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; import org.tron.api.GrpcAPI.TransactionApprovedList; import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.utils.TransactionUtil; import org.tron.protos.Protocol.Transaction; -public class UtilTest { +public class UtilTest extends BaseTest { - private static Wallet wallet; - private static String dbPath = "output_util_test"; - private static TronApplicationContext context; - private static TransactionUtil transactionUtil; + @Resource + private Wallet wallet; + @Resource + private TransactionUtil transactionUtil; static { + dbPath = "output_util_test"; Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); - transactionUtil = context.getBean(TransactionUtil.class); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java index 64d44955536..06bc5f561c5 100644 --- a/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java +++ b/framework/src/test/java/org/tron/core/services/http/solidity/GetTransactionByIdSolidityServletTest.java @@ -59,7 +59,7 @@ public static void init() { */ @Before - public void setUp() throws InterruptedException { + public void setUp() { getTransactionByIdSolidityServlet = new GetTransactionByIdSolidityServlet(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); @@ -96,7 +96,7 @@ public void doPostTest() throws IOException { httpUrlConnection.setDoOutput(true); String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -121,14 +121,15 @@ public void doPostTest() throws IOException { while ((line = in.readLine()) != null) { result.append(line).append("\n"); } + Assert.assertNotNull(result); in.close(); writer.flush(); FileInputStream fileInputStream = new FileInputStream("temp.txt"); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } @@ -150,7 +151,7 @@ public void doGetTest() throws IOException { httpUrlConnection.setDoOutput(true); String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -175,14 +176,15 @@ public void doGetTest() throws IOException { while ((line = in.readLine()) != null) { result.append(line).append("\n"); } + Assert.assertNotNull(result); in.close(); writer.flush(); FileInputStream fileInputStream = new FileInputStream("temp.txt"); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java b/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java new file mode 100644 index 00000000000..b2f4915df1e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java @@ -0,0 +1,28 @@ +package org.tron.core.services.ratelimiter; + +import java.lang.reflect.Field; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GlobalRateLimiterTest { + + @Test + public void testAcquire() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + RuntimeData runtimeData = new RuntimeData(null); + Field field = runtimeData.getClass().getDeclaredField("address"); + field.setAccessible(true); + field.set(runtimeData, "127.0.0.1"); + Assert.assertEquals(runtimeData.getRemoteAddr(), "127.0.0.1"); + GlobalRateLimiter.acquire(runtimeData); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java index 844e3ff4ae0..72ac126e394 100644 --- a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java @@ -5,7 +5,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import org.junit.Assert; -import org.testng.annotations.Test; +import org.junit.Test; import org.tron.common.utils.ReflectUtils; import org.tron.core.services.ratelimiter.adapter.GlobalPreemptibleAdapter; import org.tron.core.services.ratelimiter.adapter.IPQPSRateLimiterAdapter; @@ -23,20 +23,19 @@ public void testStrategy() { IPQpsStrategy strategy1 = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter1, "strategy"); - Assert.assertTrue(Double.valueOf( + Assert.assertEquals(5.0d, Double.parseDouble( ReflectUtils.getFieldValue(strategy1.getMapParams().get("qps"), - "value").toString()) - == 5.0d); - Assert.assertTrue(strategy1.getMapParams().get("notExist") == null); + "value").toString()), 0.0); + Assert.assertNull(strategy1.getMapParams().get("notExist")); String paramString2 = "qps=5xyz"; IPQPSRateLimiterAdapter adapter2 = new IPQPSRateLimiterAdapter(paramString2); IPQpsStrategy strategy2 = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter2, "strategy"); - Assert.assertTrue(Double.valueOf( + Assert.assertEquals(IPQpsStrategy.DEFAULT_IPQPS, Double.valueOf( ReflectUtils.getFieldValue(strategy2.getMapParams().get("qps"), - "value").toString()).equals(IPQpsStrategy.DEFAULT_IPQPS)); + "value").toString())); } @Test @@ -46,9 +45,9 @@ public void testIPQPSRateLimiterAdapter() { IPQpsStrategy strategy = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter, "strategy"); - Assert.assertTrue(Double - .valueOf(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), - "value").toString()) == 5.0d); + Assert.assertEquals(5.0d, Double + .parseDouble(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), + "value").toString()), 0.0); long t0 = System.currentTimeMillis(); for (int i = 0; i < 20; i++) { @@ -61,7 +60,7 @@ public void testIPQPSRateLimiterAdapter() { for (int i = 0; i < 20; i++) { if (i % 2 == 0) { strategy.acquire("1.2.3.4"); - } else if (i % 2 == 1) { + } else { strategy.acquire("4.3.2.1"); } } @@ -69,7 +68,7 @@ public void testIPQPSRateLimiterAdapter() { Assert.assertTrue(t1 - t0 > 1500); Cache ipLimiter = (Cache) ReflectUtils .getFieldObject(strategy, "ipLimiter"); - Assert.assertTrue(ipLimiter.size() == 2); + Assert.assertEquals(2, ipLimiter.size()); } @Test @@ -78,9 +77,9 @@ public void testGlobalPreemptibleAdapter() { GlobalPreemptibleAdapter adapter1 = new GlobalPreemptibleAdapter(paramString1); GlobalPreemptibleStrategy strategy1 = (GlobalPreemptibleStrategy) ReflectUtils .getFieldObject(adapter1, "strategy"); - Assert.assertTrue(Integer.valueOf( + Assert.assertEquals(1, Integer.parseInt( ReflectUtils.getFieldValue(strategy1.getMapParams().get("permit"), - "value").toString()) == 1); + "value").toString())); boolean first = strategy1.acquire(); Assert.assertTrue(first); @@ -95,9 +94,9 @@ public void testGlobalPreemptibleAdapter() { GlobalPreemptibleAdapter adapter2 = new GlobalPreemptibleAdapter(paramString2); GlobalPreemptibleStrategy strategy2 = (GlobalPreemptibleStrategy) ReflectUtils .getFieldObject(adapter2, "strategy"); - Assert.assertTrue(Integer.valueOf( + Assert.assertEquals(3, Integer.parseInt( ReflectUtils.getFieldValue(strategy2.getMapParams().get("permit"), - "value").toString()) == 3); + "value").toString())); first = strategy2.acquire(); Assert.assertTrue(first); @@ -114,11 +113,11 @@ public void testGlobalPreemptibleAdapter() { Assert.assertTrue(fourAfterOneRelease); Semaphore sp = (Semaphore) ReflectUtils.getFieldObject(strategy2, "sp"); - Assert.assertTrue(sp.availablePermits() == 0); + Assert.assertEquals(0, sp.availablePermits()); strategy2.release(); strategy2.release(); strategy2.release(); - Assert.assertTrue(sp.availablePermits() == 3); + Assert.assertEquals(3, sp.availablePermits()); } @@ -128,9 +127,9 @@ public void testQpsRateLimiterAdapter() { QpsRateLimiterAdapter adapter = new QpsRateLimiterAdapter(paramString); QpsStrategy strategy = (QpsStrategy) ReflectUtils.getFieldObject(adapter, "strategy"); - Assert.assertTrue(Double - .valueOf(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), - "value").toString()) == 5); + Assert.assertEquals(5, Double + .parseDouble(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), + "value").toString()), 0.0); strategy.acquire(); long t0 = System.currentTimeMillis(); diff --git a/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java b/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java index d012587849b..617e824c58f 100644 --- a/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java +++ b/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java @@ -7,6 +7,8 @@ import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @@ -21,6 +23,8 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; import org.tron.consensus.dpos.DposSlot; @@ -43,8 +47,10 @@ public abstract class ConditionallyStopTest extends BlockGenerate { static ChainBaseManager chainManager; private static DposSlot dposSlot; - private final String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + + private final String key = PublicMethod.getRandomPrivateKey(); private final byte[] privateKey = ByteArray.fromHexString(key); + private final AtomicInteger port = new AtomicInteger(0); protected String dbPath; protected Manager dbManager; @@ -52,6 +58,7 @@ public abstract class ConditionallyStopTest extends BlockGenerate { private TronNetDelegate tronNetDelegate; private TronApplicationContext context; + static LocalDateTime localDateTime = LocalDateTime.now(); private long time = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli(); @@ -71,6 +78,7 @@ public void init() throws Exception { logger.info("Full node running."); Args.setParam(new String[] {"-d", dbPath, "-w"}, Constant.TEST_CONF); Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); + initParameter(Args.getInstance()); context = new TronApplicationContext(DefaultConfig.class); @@ -84,6 +92,16 @@ public void init() throws Exception { tronNetDelegate.setExit(false); currentHeader = dbManager.getDynamicPropertiesStore() .getLatestBlockHeaderNumberFromDB(); + + byte[] address = PublicMethod.getAddressByteByPrivateKey(key); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); } @After @@ -107,8 +125,6 @@ private void generateBlock(Map witnessAndAccount) throws Exc @Test public void testStop() throws Exception { - - final ECKey ecKey = ECKey.fromPrivate(privateKey); Assert.assertNotNull(ecKey); byte[] address = ecKey.getAddress(); diff --git a/framework/src/test/java/org/tron/core/tire/TrieTest.java b/framework/src/test/java/org/tron/core/tire/TrieTest.java index 103972b2e91..ba5c536c987 100644 --- a/framework/src/test/java/org/tron/core/tire/TrieTest.java +++ b/framework/src/test/java/org/tron/core/tire/TrieTest.java @@ -136,7 +136,7 @@ public void testOrder() { trie2.put(RLP.encodeInt(i), String.valueOf(i).getBytes()); } byte[] rootHash2 = trie2.getRootHash(); - Assert.assertTrue(java.util.Arrays.equals(rootHash1, rootHash2)); + Assert.assertArrayEquals(rootHash1, rootHash2); } private void assertTrue(byte[] key, TrieImpl trieCopy) { diff --git a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java index 56e115aa325..cb502008bfc 100644 --- a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java @@ -1,57 +1,46 @@ package org.tron.core.witness; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; import org.tron.core.consensus.ProposalController; -import org.tron.core.db.Manager; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Proposal; import org.tron.protos.Protocol.Proposal.State; -public class ProposalControllerTest { +public class ProposalControllerTest extends BaseTest { - private static Manager dbManager; - private static ConsensusService consensusService; - private static TronApplicationContext context; - private static String dbPath = "output_proposal_controller_test"; + @Resource + private ConsensusService consensusService; private static ProposalController proposalController; + private static boolean init; static { + dbPath = "output_proposal_controller_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - consensusService = context.getBean(ConsensusService.class); + @Before + public void init() { + if (init) { + return; + } consensusService.start(); - proposalController = ProposalController - .createInstance(dbManager); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + proposalController = ProposalController.createInstance(dbManager); + init = true; } @Test @@ -199,7 +188,7 @@ public void testHasMostApprovals() { proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); } - Assert.assertEquals(true, proposalCapsule.hasMostApprovals(activeWitnesses)); + Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); proposalCapsule.clearApproval(); for (int i = 1; i < 18; i++) { @@ -214,10 +203,7 @@ public void testHasMostApprovals() { for (int i = 0; i < 3; i++) { proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); } - Assert.assertEquals(true, proposalCapsule.hasMostApprovals(activeWitnesses)); - - + Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); } - } diff --git a/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java b/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java index 665b5049bfc..dcca6e4bc65 100644 --- a/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java @@ -3,51 +3,25 @@ import static org.junit.Assert.assertEquals; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import javax.annotation.Resource; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.consensus.dpos.DposSlot; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -public class WitnessControllerTest { +public class WitnessControllerTest extends BaseTest { - private static Manager dbManager = new Manager(); - private static DposSlot dposSlot; - private static ChainBaseManager chainBaseManager; + @Resource + private DposSlot dposSlot; - private static TronApplicationContext context; - private static String dbPath = "output_witness_controller_test"; static { + dbPath = "output_witness_controller_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - ByteString blank = ByteString.copyFrom(new byte[1]); - - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - - dposSlot = context.getBean(DposSlot.class); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java index 2556b1b3005..55223bccb0c 100644 --- a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java @@ -1,5 +1,9 @@ package org.tron.core.zksnark; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; import static org.tron.common.zksnark.JLibrustzcash.librustzcashCheckDiversifier; import static org.tron.common.zksnark.JLibrustzcash.librustzcashComputeCm; import static org.tron.common.zksnark.JLibrustzcash.librustzcashIvkToPkd; @@ -11,23 +15,20 @@ import static org.tron.common.zksnark.JLibsodium.CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES; import com.google.protobuf.ByteString; -import java.io.File; +import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; import java.util.stream.LongStream; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; @@ -46,7 +47,6 @@ import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.SpendDescriptionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ZksnarkException; @@ -65,15 +65,15 @@ import org.tron.protos.contract.ShieldContract.PedersenHash; @Slf4j -public class LibrustzcashTest { +public class LibrustzcashTest extends BaseTest { + private static final String dbDirectory = "db_Librustzcash_test"; + private static final String indexDirectory = "index_Librustzcash_test"; + @Resource + private Wallet wallet; - private static String dbPath = "output_Librustzcash_test"; - private static String dbDirectory = "db_Librustzcash_test"; - private static String indexDirectory = "index_Librustzcash_test"; - private static AnnotationConfigApplicationContext context; - private static Wallet wallet; - - static { + @BeforeClass + public static void init() { + dbPath = "output_Librustzcash_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -84,23 +84,9 @@ public class LibrustzcashTest { }, "config-test-mainnet.conf" ); - - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); Args.setFullNodeAllowShieldedTransaction(true); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - private static int randomInt(int minInt, int maxInt) { return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); } @@ -117,21 +103,19 @@ public static void test(byte[] K, byte[] ovk, byte[] cv, byte[] cm, byte[] epk) byte[] personalization = new byte[16]; byte[] aa = "Zcash_Derive_ock".getBytes(); System.arraycopy(aa, 0, personalization, 0, aa.length); - Assert.assertTrue( - JLibsodium.cryptoGenerichashBlack2bSaltPersonal( - new Black2bSaltPersonalParams(K, 32, block, 128, null, 0, // No key. - null, // No salt. - personalization)) == 0); + assertEquals(0, JLibsodium.cryptoGenerichashBlack2bSaltPersonal( + new Black2bSaltPersonalParams(K, 32, block, 128, null, 0, // No key. + null, // No salt. + personalization))); byte[] cipher_nonce = new byte[CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES]; - Assert.assertTrue(JLibsodium + assertNotEquals(0, JLibsodium .cryptoAeadChacha20poly1305IetfDecrypt(new Chacha20poly1305IetfDecryptParams( new byte[1024], null, null, new byte[1024], 1024, - null, 0, cipher_nonce, K)) != 0); + null, 0, cipher_nonce, K))); } public static void librustzcashInitZksnarkParams() { - FullNodeHttpApiService.librustzcashInitZksnarkParams(); } @@ -148,8 +132,6 @@ public void testLibsodium() throws ZksnarkException { @Test public void testZcashParam() throws ZksnarkException { byte[] d = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - //byte[] d ={}; - //byte[] pkD = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; byte[] ivk = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; @@ -161,7 +143,7 @@ public void testZcashParam() throws ZksnarkException { (byte) 0xb4, 0x7d, 0x0e}; byte[] cm = new byte[32]; boolean check_d = librustzcashCheckDiversifier(d); - Assert.assertTrue(check_d); + assertTrue(check_d); //Most significant five bits of ivk must be 0. ivk[31] = (byte) 0x07; @@ -173,10 +155,10 @@ public void testZcashParam() throws ZksnarkException { System.out.printf("\n"); } } - Assert.assertTrue(check_pkd); + assertTrue(check_pkd); boolean res = librustzcashComputeCm(new ComputeCmParams(d, pkD, value, r, cm)); - Assert.assertFalse(res); + assertFalse(res); //check range of alpha byte[] ask = {(byte) 0xb7, 0x2c, (byte) 0xf7, (byte) 0xd6, 0x5e, 0x0e, (byte) 0x97, (byte) 0xd0, @@ -196,14 +178,14 @@ public void testZcashParam() throws ZksnarkException { boolean boolSigRes = librustzcashSaplingSpendSig( new SpendSigParams(ask, alpha, sighash, sigRes)); - Assert.assertFalse(boolSigRes); + assertFalse(boolSigRes); byte[] nsk = {(byte) 0xb6, 0x2c, (byte) 0xf7, (byte) 0xd6, 0x5e, 0x0e, (byte) 0x97, (byte) 0xd0, (byte) 0x82, 0x10, (byte) 0xc8, (byte) 0xcc, (byte) 0x93, 0x20, 0x68, (byte) 0xa6, 0x00, 0x3b, 0x34, 0x01, 0x01, 0x3b, 0x67, 0x06, (byte) 0xa9, (byte) 0xaf, 0x33, 0x65, (byte) 0xea, (byte) 0xb4, 0x7d, 0x0e}; - byte[] nk = new byte[32]; + byte[] nk; nk = librustzcashNskToNk(nsk); for (int j = 0; j < 32; j++) { @@ -217,7 +199,7 @@ public void testZcashParam() throws ZksnarkException { byte[] resbindSig = new byte[64]; boolean boolBindSig = librustzcashSaplingBindingSig( new BindingSigParams(ctx, value, sighash, resbindSig)); - Assert.assertFalse(boolBindSig); + assertFalse(boolBindSig); JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); } @@ -284,15 +266,14 @@ public long benchmarkCreateSpend() throws ZksnarkException { zkproof)); JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); - long time = (System.currentTimeMillis() - start); - System.out.println("--- time is: " + time + ", result is " + ret); + assertTrue(ret); return time; } - // @Test + @Ignore + @Test public void calBenchmarkSpendConcurrent() throws Exception { librustzcashInitZksnarkParams(); System.out.println("--- load ok ---"); @@ -307,24 +288,17 @@ public void calBenchmarkSpendConcurrent() throws Exception { ExecutorService generatePool = Executors.newFixedThreadPool( availableProcessors, - new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "generate-transaction"); - } - }); + r -> new Thread(r, "generate-transaction")); long startGenerate = System.currentTimeMillis(); - LongStream.range(0L, count).forEach(l -> { - generatePool.execute(() -> { - try { - benchmarkCreateSpend(); - } catch (Exception ex) { - ex.printStackTrace(); - logger.error("", ex); - } - }); - }); + LongStream.range(0L, count).forEach(l -> generatePool.execute(() -> { + try { + benchmarkCreateSpend(); + } catch (Exception ex) { + ex.printStackTrace(); + logger.error("", ex); + } + })); countDownLatch.await(); @@ -466,7 +440,7 @@ public long benchmarkCreateSaplingOutput() throws BadItemException, ZksnarkExcep JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(result); + assertTrue(result); long endTime = System.currentTimeMillis(); long time = endTime - startTime; @@ -526,7 +500,7 @@ public void checkVerifyOutErr() throws ZksnarkException { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(result); + assertFalse(result); } @Test @@ -550,19 +524,20 @@ public void testGenerateNote() throws Exception { try { Optional op = incomingViewingKey.address(diversifierT); // PaymentAddress op = spendingKey.defaultAddress(); - - Note note = new Note(op.get(), 100); - note.setRcm(ByteArray - .fromHexString( - "bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - byte[] cm = note.cm(); - if (cm != null) { - success++; - } else { - fail++; + if (op.isPresent()) { + Note note = new Note(op.get(), 100); + note.setRcm(ByteArray + .fromHexString( + "bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); + + byte[] cm = note.cm(); + if (cm != null) { + success++; + } else { + fail++; + } + System.out.println("note is " + Arrays.toString(cm)); } - System.out.println("note is " + note.cm()); } catch (ZksnarkException e) { System.out.println("failed: " + e.getMessage()); fail++; @@ -573,7 +548,7 @@ public void testGenerateNote() throws Exception { System.out.println("success is: " + success); System.out.println("fail is: " + fail); - Assert.assertEquals(0, fail); + assertEquals(0, fail); } @Test @@ -615,7 +590,7 @@ public void testGenerateNoteWithDefault() throws Exception { System.out.println("success is: " + success); System.out.println("fail is: " + fail); - Assert.assertEquals(0, fail); + assertEquals(0, fail); } @Test @@ -635,13 +610,14 @@ public void testGenerateNoteWithConstant() throws Exception { try { Optional op = incomingViewingKey.address(diversifierT); // PaymentAddress op = spendingKey.defaultAddress(); + if (op.isPresent()) { + Note note = new Note(op.get(), randomInt(100, 100000)); + note.setRcm(ByteArray + .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - Note note = new Note(op.get(), randomInt(100, 100000)); - note.setRcm(ByteArray - .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - byte[] cm = note.cm(); - System.out.println("note is " + note.cm()); + byte[] cm = note.cm(); + System.out.println("note is " + Arrays.toString(cm)); + } } catch (ZksnarkException e) { System.out.println("failed: " + e.getMessage()); } @@ -659,7 +635,7 @@ public void testPedersenHash() throws Exception { byte[] res = new byte[32]; JLibrustzcash.librustzcashMerkleHash(new MerkleHashParams(25, a, b, res)); - Assert.assertEquals("61a50a5540b4944da27cbd9b3d6ec39234ba229d2c461f4d719bc136573bf45b", + assertEquals("61a50a5540b4944da27cbd9b3d6ec39234ba229d2c461f4d719bc136573bf45b", ByteArray.toHexString(res)); } } diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java index 60c5dd43eac..678eb137df0 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java @@ -2,19 +2,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Arrays; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; -import org.tron.common.zksnark.MerkleContainer; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; @@ -23,9 +18,7 @@ import org.tron.core.capsule.IncrementalMerkleVoucherCapsule; import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; @@ -37,38 +30,29 @@ import org.tron.protos.contract.ShieldContract.ReceiveDescription; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; -public class MerkleContainerTest { +public class MerkleContainerTest extends BaseTest { - private static Manager dbManager = new Manager(); - private static TronApplicationContext context; - private static String dbPath = "MerkleContainerTest"; - private static MerkleContainer merkleContainer; + @Resource + private Wallet wallet; + // private static MerkleContainer merkleContainer; static { + dbPath = "MerkleContainerTest"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + /*@Before + public void init() { merkleContainer = MerkleContainer .createInstance(dbManager.getMerkleTreeStore(), dbManager.getChainBaseManager() .getMerkleTreeIndexStore()); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } + }*/ - @Test + /*@Test public void test() { //add - /*IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( + IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( new IncrementalMerkleTreeCapsule()); String s1 = "2ec45f5ae2d1bc7a80df02abfb2814a1239f956c6fb3ac0e112c008ba2c1ab91"; PedersenHashCapsule compressCapsule1 = new PedersenHashCapsule(); @@ -164,9 +148,9 @@ public void test() { .putMerkleVoucherIntoStore(witness.getMerkleVoucherKey(), witness.getVoucherCapsule()); IncrementalMerkleTreeContainer bestMerkleRoot = merkleContainer.getBestMerkle(); - Assert.assertEquals(1, bestMerkleRoot.size());*/ + Assert.assertEquals(1, bestMerkleRoot.size()); - } + }*/ private Transaction createTransaction(String strCm1, String strCm2) { ByteString cm1 = ByteString.copyFrom(ByteArray.fromHexString(strCm1)); @@ -182,9 +166,8 @@ private Transaction createTransaction(String strCm1, String strCm2) { Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) .setParameter( Any.pack(contract)).build()); - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) + return Transaction.newBuilder().setRawData(transactionBuilder.build()) .build(); - return transaction; } private void initMerkleTreeWitnessInfo() throws ZksnarkException { @@ -361,7 +344,6 @@ public void getMerkleTreeWitnessInfoTest() throws Exception { OutputPointInfo outputPointInfo = OutputPointInfo.newBuilder().addOutPoints(outputPoint1) .addOutPoints(outputPoint2).setBlockNum(number).build(); // Args.getInstance().setAllowShieldedTransaction(1); - Wallet wallet = context.getBean(Wallet.class); IncrementalMerkleVoucherInfo merkleTreeWitnessInfo = wallet .getMerkleTreeVoucherInfo(outputPointInfo); @@ -426,7 +408,7 @@ public void append() throws ZksnarkException { byte[] roota = witnessa.root().getContent().toByteArray(); byte[] rootb = witnessb.root().getContent().toByteArray(); - Assert.assertTrue(Arrays.equals(roota, rootb)); + Assert.assertArrayEquals(roota, rootb); } } diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java index 155d5aee11a..b635b55339c 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java @@ -6,40 +6,32 @@ import com.google.protobuf.ByteString; import java.io.File; import java.util.List; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleTreeContainer.EmptyMerkleRoots; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.MerklePath; -import org.tron.core.Wallet; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.IncrementalMerkleVoucherCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.contract.ShieldContract.PedersenHash; -public class MerkleTreeTest { +public class MerkleTreeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_ShieldedTransaction_test"; - private static String dbDirectory = "db_ShieldedTransaction_test"; - private static String indexDirectory = "index_ShieldedTransaction_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + private static final String dbDirectory = "db_ShieldedTransaction_test"; + private static final String indexDirectory = "index_ShieldedTransaction_test"; + private static boolean init; static { + dbPath = "output_ShieldedTransaction_test"; Args.setParam( new String[]{ "--output-directory", dbPath, @@ -50,28 +42,21 @@ public class MerkleTreeTest { }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } private JSONArray readFile(String fileName) throws Exception { @@ -80,10 +65,8 @@ private JSONArray readFile(String fileName) throws Exception { List readLines = Files.readLines(new File(file1), Charsets.UTF_8); - JSONArray array = JSONArray + return JSONArray .parseArray(readLines.stream().reduce((s, s2) -> s + s2).get()); - - return array; } private String PedersenHash2String(PedersenHash hash) { diff --git a/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java b/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java index f77a85b5bc1..e2b8ef43306 100644 --- a/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java @@ -1,22 +1,17 @@ package org.tron.core.zksnark; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Optional; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Wallet; import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; import org.tron.core.zen.note.Note; import org.tron.core.zen.note.NoteEncryption.Encryption; @@ -25,7 +20,7 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class NoteEncDecryTest { +public class NoteEncDecryTest extends BaseTest { private static final String dbPath = "note_encdec_test"; private static final String FROM_ADDRESS; @@ -41,13 +36,12 @@ public class NoteEncDecryTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static Manager dbManager; - private static TronApplicationContext context; - private static Wallet wallet; + private static boolean init; + @Resource + private Wallet wallet; static { Args.setParam(new String[]{"--output-directory", dbPath}, "config-localtest.conf"); - context = new TronApplicationContext(DefaultConfig.class); FROM_ADDRESS = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; } @@ -55,28 +49,15 @@ public class NoteEncDecryTest { /** * Init data. */ - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //give a big value for pool, avoid for dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(10_000_000_000L); // Args.getInstance().setAllowShieldedTransaction(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** diff --git a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java index 1eb5becffb6..cd7a36ab7a4 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -10,20 +10,20 @@ import java.io.File; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Optional; -import org.junit.AfterClass; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.testng.collections.Lists; import org.tron.api.GrpcAPI; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleTreeContainer.EmptyMerkleRoots; @@ -50,9 +50,7 @@ import org.tron.core.capsule.SpendDescriptionCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ContractExeException; @@ -90,7 +88,8 @@ import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; import org.tron.protos.contract.ShieldContract.SpendDescription; -public class SendCoinShieldTest { +@Slf4j +public class SendCoinShieldTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; private static final byte[] DEFAULT_OVK; @@ -105,16 +104,15 @@ public class SendCoinShieldTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static String dbPath = "output_ShieldedTransaction_test"; - private static String dbDirectory = "db_ShieldedTransaction_test"; - private static String indexDirectory = "index_ShieldedTransaction_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + @Resource + private Wallet wallet; + + private static boolean init; static { + dbPath = "output_ShieldedTransaction_test"; Args.setParam(new String[]{"--output-directory", dbPath}, "config-test-mainnet.conf"); - context = new TronApplicationContext(DefaultConfig.class); + Args.getInstance().setZenTokenId(String.valueOf(tokenId)); PUBLIC_ADDRESS_ONE = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; DEFAULT_OVK = ByteArray @@ -124,49 +122,42 @@ public class SendCoinShieldTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - /** - * create temp Capsule test need. - */ - @Before - public void createCapsule() { - Args.getInstance().setZenTokenId(String.valueOf(tokenId)); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveTokenIdNum(tokenId); AssetIssueContract assetIssueContract = AssetIssueContract.newBuilder() .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(PUBLIC_ADDRESS_ONE))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) + .setName(ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString(ASSET_NAME)))) .setId(Long.toString(tokenId)).setTotalSupply(OWNER_BALANCE).setTrxNum(TRX_NUM).setNum(NUM) .setStartTime(START_TIME).setEndTime(END_TIME).setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))).build(); + .setDescription(ByteString.copyFrom( + Objects.requireNonNull(ByteArray.fromString(DESCRIPTION)))) + .setUrl(ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString(URL)))).build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + + init = true; } private void addZeroValueOutputNote(ZenTransactionBuilder builder) throws ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(DEFAULT_OVK, paymentAddress, 0, "just for decode for ovk".getBytes()); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(DEFAULT_OVK, paymentAddress, 0, "just for decode for ovk".getBytes()); + } } @Test @@ -180,7 +171,9 @@ public void testPathMock() throws ZksnarkException { List index = Lists.newArrayList(Arrays.asList(indexArray)); MerklePath path = new MerklePath(authenticationPath, index); byte[] encode = path.encode(); - System.out.print(ByteArray.toHexString(encode)); + String hexString = ByteArray.toHexString(encode); + System.out.print(hexString); + Assert.assertNotNull(hexString); } private PedersenHash String2PedersenHash(String str) { @@ -224,20 +217,21 @@ private IncrementalMerkleVoucherContainer createSimpleMerkleVoucherContainer(byt compressCapsule1.setContent(ByteString.copyFrom(cm)); PedersenHash a = compressCapsule1.getInstance(); tree.append(a); - IncrementalMerkleVoucherContainer voucher = tree.toVoucher(); - return voucher; + return tree.toVoucher(); } - private void librustzcashInitZksnarkParams() throws ZksnarkException { + private void librustzcashInitZksnarkParams() { FullNodeHttpApiService.librustzcashInitZksnarkParams(); } @Test - public void testStringRevert() throws Exception { + public void testStringRevert() { byte[] bytes = ByteArray .fromHexString("6c030e6d7460f91668cc842ceb78cdb54470469e78cd59cf903d3a6e1aa03e7c"); ByteUtil.reverse(bytes); - System.out.println("testStringRevert------" + ByteArray.toHexString(bytes)); + String hexString = ByteArray.toHexString(bytes); + System.out.println("testStringRevert------" + hexString); + Assert.assertNotNull(hexString); } @Test @@ -250,12 +244,9 @@ public void testGenerateSpendProof() throws Exception { DiversifierT diversifierT = new DiversifierT(); byte[] d; - while (true) { + do { d = org.tron.keystore.Wallet.generateRandomBytes(Constant.ZC_DIVERSIFIER_SIZE); - if (JLibrustzcash.librustzcashCheckDiversifier(d)) { - break; - } - } + } while (!JLibrustzcash.librustzcashCheckDiversifier(d)); diversifierT.setData(d); FullViewingKey fullViewingKey = expsk.fullViewingKey(); @@ -263,17 +254,19 @@ public void testGenerateSpendProof() throws Exception { IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); Optional op = incomingViewingKey.address(diversifierT); + if (op.isPresent()) { + Note note = new Note(op.get(), 100); + note.setRcm(ByteArray + .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - Note note = new Note(op.get(), 100); - note.setRcm(ByteArray - .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - IncrementalMerkleVoucherContainer voucher = createComplexMerkleVoucherContainer(note.cm()); + IncrementalMerkleVoucherContainer voucher = createComplexMerkleVoucherContainer(note.cm()); - byte[] anchor = voucher.root().getContent().toByteArray(); - SpendDescriptionInfo spend = new SpendDescriptionInfo(expsk, note, anchor, voucher); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - SpendDescriptionCapsule sdesc = builder.generateSpendProof(spend, ctx); + byte[] anchor = voucher.root().getContent().toByteArray(); + SpendDescriptionInfo spend = new SpendDescriptionInfo(expsk, note, anchor, voucher); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + SpendDescriptionCapsule sdesc = builder.generateSpendProof(spend, ctx); + Assert.assertNotNull(sdesc); + } } @Test @@ -284,11 +277,15 @@ public void generateOutputProof() throws ZksnarkException { FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); - builder.generateOutputProof(builder.getReceives().get(0), ctx); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + Assert.assertNotNull(paymentAddress); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); + builder.generateOutputProof(builder.getReceives().get(0), ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + } } @Test @@ -298,24 +295,27 @@ public void verifyOutputProof() throws ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); - ReceiveDescriptionCapsule capsule = builder - .generateOutputProof(builder.getReceives().get(0), ctx); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - ReceiveDescription receiveDescription = capsule.getInstance(); - ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); - if (!JLibrustzcash.librustzcashSaplingCheckOutput( - new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), - receiveDescription.getEpk().toByteArray(), - receiveDescription.getZkproof().toByteArray()))) { + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + Assert.assertNotNull(paymentAddress); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); + ReceiveDescriptionCapsule capsule = builder + .generateOutputProof(builder.getReceives().get(0), ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + ReceiveDescription receiveDescription = capsule.getInstance(); + ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); + if (!JLibrustzcash.librustzcashSaplingCheckOutput( + new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), + receiveDescription.getEpk().toByteArray(), + receiveDescription.getZkproof().toByteArray()))) { + JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + throw new RuntimeException("librustzcashSaplingCheckOutput error"); + } JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); - throw new RuntimeException("librustzcashSaplingCheckOutput error"); } - JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); } @@ -329,49 +329,54 @@ public void testDecryptReceiveWithIvk() throws ZksnarkException { FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, memo); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, memo); - ZenTransactionBuilder.ReceiveDescriptionInfo output = builder.getReceives().get(0); - ReceiveDescriptionCapsule receiveDescriptionCapsule = builder.generateOutputProof(output, ctx); - ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); + ZenTransactionBuilder.ReceiveDescriptionInfo output = builder.getReceives().get(0); + ReceiveDescriptionCapsule receiveDescriptionCapsule = builder + .generateOutputProof(output, ctx); + ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); - Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext - fullViewingKey.inViewingKey().getValue(), receiveDescription.getEpk().toByteArray(),//epk - receiveDescription.getNoteCommitment().toByteArray() //cm - ); + Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext + fullViewingKey.inViewingKey().getValue(), receiveDescription.getEpk().toByteArray(),//epk + receiveDescription.getNoteCommitment().toByteArray() //cm + ); - Assert.assertTrue(ret1.isPresent()); + Assert.assertTrue(ret1.isPresent()); - Note noteText = ret1.get(); - byte[] pkD = new byte[32]; - if (!JLibrustzcash.librustzcashIvkToPkd( - new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - return; - } + Note noteText = ret1.get(); + byte[] pkD = new byte[32]; + if (!JLibrustzcash.librustzcashIvkToPkd( + new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + return; + } - Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); - Assert.assertEquals(noteText.getValue(), 4000); - Assert.assertArrayEquals(noteText.getMemo(), memo); + Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); + Assert.assertEquals(4000, noteText.getValue()); + Assert.assertArrayEquals(noteText.getMemo(), memo); - String paymentAddressStr = KeyIo.encodePaymentAddress(new PaymentAddress(noteText.getD(), pkD)); + String paymentAddressStr = KeyIo.encodePaymentAddress( + new PaymentAddress(noteText.getD(), pkD)); - GrpcAPI.Note grpcAPINote = GrpcAPI.Note.newBuilder().setPaymentAddress(paymentAddressStr) - .setValue(noteText.getValue()).setRcm(ByteString.copyFrom(noteText.getRcm())) - .setMemo(ByteString.copyFrom(noteText.getMemo())).build(); + GrpcAPI.Note grpcAPINote = GrpcAPI.Note.newBuilder().setPaymentAddress(paymentAddressStr) + .setValue(noteText.getValue()).setRcm(ByteString.copyFrom(noteText.getRcm())) + .setMemo(ByteString.copyFrom(noteText.getMemo())).build(); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + } } public String byte2intstring(byte[] input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length; i++) { - sb.append(String.valueOf((int) input[i]) + ", "); + sb.append(String.valueOf(input[i])).append(", "); if (i % 16 == 15) { sb.append("\n"); } @@ -408,48 +413,50 @@ public void testDecryptReceiveWithOvk() throws Exception { byte[] cmuOpt = note.cm(); Assert.assertNotNull(cmuOpt); - NotePlaintextEncryptionResult enc = note.encrypt(pkd).get(); - NoteEncryption encryptor = enc.getNoteEncryption(); - OutgoingPlaintext outgoingPlaintext = new OutgoingPlaintext(note.getPkD(), encryptor.getEsk()); - - // encrypt with ovk - Encryption.OutCiphertext outCiphertext = outgoingPlaintext - .encrypt(fullViewingKey.getOvk(), receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), encryptor); - - // get pkD, esk from decryption of c_out with ovk - Optional ret2 = OutgoingPlaintext - .decrypt(outCiphertext, fullViewingKey.getOvk(), - receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), encryptor.getEpk()); - - if (ret2.isPresent()) { - OutgoingPlaintext decryptedOutgoingPlaintext = ret2.get(); - Assert.assertArrayEquals(decryptedOutgoingPlaintext.getPkD(), outgoingPlaintext.getPkD()); - Assert.assertArrayEquals(decryptedOutgoingPlaintext.getEsk(), outgoingPlaintext.getEsk()); - - //decrypt c_enc with pkd、esk - Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); - ciphertext.setData(enc.getEncCiphertext()); - Optional foo = Note - .decrypt(ciphertext, encryptor.getEpk(), decryptedOutgoingPlaintext.getEsk(), - decryptedOutgoingPlaintext.getPkD(), cmuOpt); - - if (foo.isPresent()) { - Note bar = foo.get(); - //verify result - Assert.assertEquals(4000, bar.getValue()); - Assert.assertArrayEquals(memo, bar.getMemo()); + Optional optional = note.encrypt(pkd); + if (optional.isPresent()) { + NotePlaintextEncryptionResult enc = optional.get(); + NoteEncryption encryptor = enc.getNoteEncryption(); + OutgoingPlaintext outgoingPlaintext = new OutgoingPlaintext( + note.getPkD(), encryptor.getEsk()); + // encrypt with ovk + Encryption.OutCiphertext outCiphertext = outgoingPlaintext + .encrypt(fullViewingKey.getOvk(), receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), encryptor); + + // get pkD, esk from decryption of c_out with ovk + Optional ret2 = OutgoingPlaintext + .decrypt(outCiphertext, fullViewingKey.getOvk(), + receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), encryptor.getEpk()); + + if (ret2.isPresent()) { + OutgoingPlaintext decryptedOutgoingPlaintext = ret2.get(); + Assert.assertArrayEquals(decryptedOutgoingPlaintext.getPkD(), outgoingPlaintext.getPkD()); + Assert.assertArrayEquals(decryptedOutgoingPlaintext.getEsk(), outgoingPlaintext.getEsk()); + + //decrypt c_enc with pkd、esk + Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); + ciphertext.setData(enc.getEncCiphertext()); + Optional foo = Note + .decrypt(ciphertext, encryptor.getEpk(), decryptedOutgoingPlaintext.getEsk(), + decryptedOutgoingPlaintext.getPkD(), cmuOpt); + + if (foo.isPresent()) { + Note bar = foo.get(); + //verify result + Assert.assertEquals(4000, bar.getValue()); + Assert.assertArrayEquals(memo, bar.getMemo()); + } else { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.fail(); + } } else { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(true); + Assert.fail(); } - } else { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(true); } - - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); } @Test @@ -483,53 +490,55 @@ public void pushShieldedTransactionAndDecryptWithIvk() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder - .addOutput(senderOvk, paymentAddress, 1000 * 1000000L - wallet.getShieldedTransactionFee(), - memo); - - TransactionCapsule transactionCap = builder.build(); - - boolean ok = dbManager.pushTransaction(transactionCap); - Assert.assertTrue(ok); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(senderOvk, paymentAddress, + 1000 * 1000000L - wallet.getShieldedTransactionFee(), memo); - // add here - byte[] ivk = incomingViewingKey.getValue(); - Protocol.Transaction t = transactionCap.getInstance(); + TransactionCapsule transactionCap = builder.build(); - for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { - if (c.getType() != ContractType.ShieldedTransferContract) { - continue; - } - ShieldedTransferContract stContract = c.getParameter() - .unpack(ShieldedTransferContract.class); - ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + boolean ok = dbManager.pushTransaction(transactionCap); + Assert.assertTrue(ok); - Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext - ivk, receiveDescription.getEpk().toByteArray(),//epk - receiveDescription.getNoteCommitment().toByteArray() //cm - ); + // add here + byte[] ivk = incomingViewingKey.getValue(); + Protocol.Transaction t = transactionCap.getInstance(); - if (ret1.isPresent()) { - Note noteText = ret1.get(); - byte[] pkD = new byte[32]; - if (!JLibrustzcash.librustzcashIvkToPkd( - new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - return; + for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { + if (c.getType() != ContractType.ShieldedTransferContract) { + continue; + } + ShieldedTransferContract stContract = c.getParameter() + .unpack(ShieldedTransferContract.class); + ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + + Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext + ivk, receiveDescription.getEpk().toByteArray(),//epk + receiveDescription.getNoteCommitment().toByteArray() //cm + ); + + if (ret1.isPresent()) { + Note noteText = ret1.get(); + byte[] pkD = new byte[32]; + if (!JLibrustzcash.librustzcashIvkToPkd( + new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + return; + } + Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); + Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), + noteText.getValue()); + Assert.assertArrayEquals(memo, noteText.getMemo()); + } else { + Assert.fail(); } - Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); - Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), - noteText.getValue()); - Assert.assertArrayEquals(memo, noteText.getMemo()); - } else { - Assert.assertFalse(true); } + // end here + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); } - // end here - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); } @Test @@ -570,59 +579,61 @@ public void pushShieldedTransactionAndDecryptWithOvk() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder - .addOutput(senderOvk, paymentAddress, 1000 * 1000000L - wallet.getShieldedTransactionFee(), - memo); - - TransactionCapsule transactionCap = builder.build(); - boolean ok = dbManager.pushTransaction(transactionCap); - Assert.assertTrue(ok); - - // add here - Protocol.Transaction t = transactionCap.getInstance(); - for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { - if (c.getType() != Protocol.Transaction.Contract.ContractType.ShieldedTransferContract) { - continue; - } - ShieldedTransferContract stContract = c.getParameter() - .unpack(ShieldedTransferContract.class); - ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); - - //first try to decrypt cOut with ovk, get pkd、esk - Encryption.OutCiphertext cOut = new Encryption.OutCiphertext(); - cOut.setData(receiveDescription.getCOut().toByteArray()); - Optional notePlaintext = OutgoingPlaintext.decrypt(cOut,//ciphertext - senderOvk, receiveDescription.getValueCommitment().toByteArray(), //cv - receiveDescription.getNoteCommitment().toByteArray(), //cmu - receiveDescription.getEpk().toByteArray() //epk - ); - - //then decrypt c_enc with pkd、esk, get decoded note == ciphertext - if (notePlaintext.isPresent()) { - OutgoingPlaintext decryptedOutgoingPlaintext = notePlaintext.get(); - - Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); - ciphertext.setData(receiveDescription.getCEnc().toByteArray()); - Optional foo = Note.decrypt(ciphertext, receiveDescription.getEpk().toByteArray(), - decryptedOutgoingPlaintext.getEsk(), decryptedOutgoingPlaintext.getPkD(), - receiveDescription.getNoteCommitment().toByteArray()); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(senderOvk, paymentAddress, + 1000 * 1000000L - wallet.getShieldedTransactionFee(), memo); - if (foo.isPresent()) { - Note bar = foo.get(); - //verify result - Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), bar.getValue()); - Assert.assertArrayEquals(memo, bar.getMemo()); - } else { - Assert.assertFalse(true); + TransactionCapsule transactionCap = builder.build(); + boolean ok = dbManager.pushTransaction(transactionCap); + Assert.assertTrue(ok); + + // add here + Protocol.Transaction t = transactionCap.getInstance(); + for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { + if (c.getType() != Protocol.Transaction.Contract.ContractType.ShieldedTransferContract) { + continue; + } + ShieldedTransferContract stContract = c.getParameter() + .unpack(ShieldedTransferContract.class); + ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + + //first try to decrypt cOut with ovk, get pkd、esk + Encryption.OutCiphertext cOut = new Encryption.OutCiphertext(); + cOut.setData(receiveDescription.getCOut().toByteArray()); + Optional notePlaintext = OutgoingPlaintext.decrypt(cOut,//ciphertext + senderOvk, receiveDescription.getValueCommitment().toByteArray(), //cv + receiveDescription.getNoteCommitment().toByteArray(), //cmu + receiveDescription.getEpk().toByteArray() //epk + ); + + //then decrypt c_enc with pkd、esk, get decoded note == ciphertext + if (notePlaintext.isPresent()) { + OutgoingPlaintext decryptedOutgoingPlaintext = notePlaintext.get(); + + Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); + ciphertext.setData(receiveDescription.getCEnc().toByteArray()); + Optional foo = Note.decrypt(ciphertext, receiveDescription.getEpk().toByteArray(), + decryptedOutgoingPlaintext.getEsk(), decryptedOutgoingPlaintext.getPkD(), + receiveDescription.getNoteCommitment().toByteArray()); + + if (foo.isPresent()) { + Note bar = foo.get(); + //verify result + Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), + bar.getValue()); + Assert.assertArrayEquals(memo, bar.getMemo()); + } else { + Assert.fail(); + } } } + // end here + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); } - // end here - - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); } private byte[] getHash() { @@ -630,6 +641,8 @@ private byte[] getHash() { .getInstance().isECKeyCryptoEngine(), "this is a test".getBytes()).getBytes(); } + @Ignore + @Test public void checkZksnark() throws BadItemException, ZksnarkException { librustzcashInitZksnarkParams(); long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); @@ -652,14 +665,17 @@ public void checkZksnark() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - TransactionCapsule transactionCap = builder.build(); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - boolean ret = ZksnarkClient.getInstance().checkZksnarkProof(transactionCap.getInstance(), - getShieldTransactionHashIgnoreTypeException(transactionCap.getInstance()), - 10 * 1000000); - Assert.assertTrue(ret); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + TransactionCapsule transactionCap = builder.build(); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + boolean ret = ZksnarkClient.getInstance().checkZksnarkProof(transactionCap.getInstance(), + getShieldTransactionHashIgnoreTypeException(transactionCap.getInstance()), + 10 * 1000000); + Assert.assertTrue(ret); + } } @Test @@ -695,7 +711,7 @@ public void testVerifySpendProof() throws BadItemException, ZksnarkException { spendDescriptionCapsule.getRk().toByteArray(), spendDescriptionCapsule.getZkproof().toByteArray(), result, getHash())); JLibrustzcash.librustzcashSaplingVerificationCtxFree(verifyContext); - Assert.assertEquals(ok, true); + Assert.assertTrue(ok); } @Test @@ -717,16 +733,19 @@ public void saplingBindingSig() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - builder.generateOutputProof(builder.getReceives().get(0), ctx); - - // test create binding sig - byte[] bindingSig = new byte[64]; - boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( - new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + builder.generateOutputProof(builder.getReceives().get(0), ctx); + + // test create binding sig + byte[] bindingSig = new byte[64]; + boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( + new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ret); + } } @Test @@ -756,13 +775,16 @@ public void pushShieldedTransaction() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, - 4010 * 1000000L - wallet.getShieldedTransactionFee(), new byte[512]); - TransactionCapsule transactionCap = builder.build(); - boolean ok = dbManager.pushTransaction(transactionCap); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, + 4010 * 1000000L - wallet.getShieldedTransactionFee(), new byte[512]); + TransactionCapsule transactionCap = builder.build(); + boolean ok = dbManager.pushTransaction(transactionCap); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); + } } @Test @@ -785,46 +807,49 @@ public void finalCheck() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - ReceiveDescriptionCapsule receiveDescriptionCapsule = builder - .generateOutputProof(builder.getReceives().get(0), ctx); - - //create binding sig - byte[] bindingSig = new byte[64]; - boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( - new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); - // check spend - ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); - byte[] result = new byte[64]; - JLibrustzcash.librustzcashSaplingSpendSig( - new SpendSigParams(expsk.getAsk(), builder.getSpends().get(0).getAlpha(), getHash(), - result)); - - SpendDescription spendDescription = spendDescriptionCapsule.getInstance(); - boolean ok; - ok = JLibrustzcash.librustzcashSaplingCheckSpend( - new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), - spendDescription.getAnchor().toByteArray(), - spendDescription.getNullifier().toByteArray(), spendDescription.getRk().toByteArray(), - spendDescription.getZkproof().toByteArray(), result, getHash())); - Assert.assertTrue(ok); - - // check output - ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); - ok = JLibrustzcash.librustzcashSaplingCheckOutput( - new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), - receiveDescription.getEpk().toByteArray(), - receiveDescription.getZkproof().toByteArray())); - Assert.assertTrue(ok); - // final check - ok = JLibrustzcash.librustzcashSaplingFinalCheck( - new FinalCheckParams(ctx, builder.getValueBalance(), bindingSig, getHash())); - Assert.assertTrue(ok); - JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + ReceiveDescriptionCapsule receiveDescriptionCapsule = builder + .generateOutputProof(builder.getReceives().get(0), ctx); + + //create binding sig + byte[] bindingSig = new byte[64]; + boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( + new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ret); + // check spend + ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); + byte[] result = new byte[64]; + JLibrustzcash.librustzcashSaplingSpendSig( + new SpendSigParams(expsk.getAsk(), builder.getSpends().get(0).getAlpha(), getHash(), + result)); + + SpendDescription spendDescription = spendDescriptionCapsule.getInstance(); + boolean ok; + ok = JLibrustzcash.librustzcashSaplingCheckSpend( + new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), + spendDescription.getAnchor().toByteArray(), + spendDescription.getNullifier().toByteArray(), spendDescription.getRk().toByteArray(), + spendDescription.getZkproof().toByteArray(), result, getHash())); + Assert.assertTrue(ok); + + // check output + ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); + ok = JLibrustzcash.librustzcashSaplingCheckOutput( + new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), + receiveDescription.getEpk().toByteArray(), + receiveDescription.getZkproof().toByteArray())); + Assert.assertTrue(ok); + // final check + ok = JLibrustzcash.librustzcashSaplingFinalCheck( + new FinalCheckParams(ctx, builder.getValueBalance(), bindingSig, getHash())); + Assert.assertTrue(ok); + JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + } } @Test @@ -847,11 +872,11 @@ public void testEmptyRoots() throws Exception { } private JSONArray readFile(String fileName) throws Exception { - String file1 = SendCoinShieldTest.class.getClassLoader() - .getResource("json" + File.separator + fileName).getFile(); + String file1 = Objects.requireNonNull(SendCoinShieldTest.class.getClassLoader() + .getResource("json" + File.separator + fileName)).getFile(); List readLines = Files.readLines(new File(file1), Charsets.UTF_8); - JSONArray array = JSONArray.parseArray(readLines.stream().reduce((s, s2) -> s + s2).get()); - return array; + Optional optional = readLines.stream().reduce((s, s2) -> s + s2); + return optional.map(JSONArray::parseArray).orElse(null); } @@ -864,9 +889,9 @@ public void testComputeCm() throws Exception { 9990000000L, ByteArray .fromHexString("08e3a2ff1101b628147125b786c757b483f1cf7c309f8a647055bfb1ca819c02"), result))) { - System.out.println(" error"); + Assert.fail(); } else { - System.out.println(" ok"); + Assert.assertTrue(true); } } @@ -897,12 +922,9 @@ public void getSpendingKey() throws Exception { DiversifierT diversifierT = new DiversifierT(); byte[] d; - while (true) { + do { d = org.tron.keystore.Wallet.generateRandomBytes(Constant.ZC_DIVERSIFIER_SIZE); - if (JLibrustzcash.librustzcashCheckDiversifier(d)) { - break; - } - } + } while (!JLibrustzcash.librustzcashCheckDiversifier(d)); diversifierT.setData(d); System.out.println("d is: " + ByteArray.toHexString(d)); @@ -1336,7 +1358,7 @@ public void TestCreateMultipleTxAtTheSameTime() throws Exception { executeTx(transactionCapsule); System.out.println("Success execute tx,num:" + transactionCapsule.getBlockNum()); } catch (Exception ex) { - System.out.println(ex); + logger.error("error", ex); } }); } @@ -1531,7 +1553,7 @@ public void TestGeneratesProofWithWrongRcm() throws Exception { builder.addSpend(expsk, note, anchor, voucher); SpendDescriptionCapsule spendDescriptionCapsule = builder .generateSpendProof(builder.getSpends().get(0), ctx); - + Assert.assertNotNull(spendDescriptionCapsule); } @Test @@ -1641,9 +1663,7 @@ private TransactionCapsule generateDefaultBuilder(ZenTransactionBuilder builder) String TO_ADDRESS = generateDefaultToAccount(); builder.setTransparentOutput(ByteArray.fromHexString(TO_ADDRESS), 1000 * 1000000L - wallet.getShieldedTransactionFee()); - - TransactionCapsule transactionCap = builder.build(); - return transactionCap; + return builder.build(); } @Test @@ -1770,7 +1790,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo throw e; } System.out.println("Done"); - return; } } } @@ -1807,7 +1826,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo throw e; } System.out.println("Done"); - return; } } } diff --git a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java index 71501d68a41..514a5dfab76 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -4,30 +4,28 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; import java.security.SignatureException; import java.util.List; import java.util.Optional; +import javax.annotation.Resource; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.tron.api.GrpcAPI.BytesMessage; import org.tron.api.GrpcAPI.DecryptNotes; import org.tron.api.GrpcAPI.ReceiveNote; import org.tron.api.GrpcAPI.SpendAuthSigParameters; import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; @@ -37,7 +35,6 @@ import org.tron.common.zksnark.LibrustzcashParam.IvkToPkdParams; import org.tron.common.zksnark.LibrustzcashParam.OutputProofParams; import org.tron.common.zksnark.LibrustzcashParam.SpendSigParams; -import org.tron.core.ChainBaseManager; import org.tron.core.Wallet; import org.tron.core.actuator.Actuator; import org.tron.core.actuator.ActuatorCreator; @@ -52,11 +49,8 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.BlockGenerate; -import org.tron.core.db.Manager; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ContractExeException; @@ -101,12 +95,10 @@ import org.tron.protos.contract.ShieldContract.ReceiveDescription; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; import org.tron.protos.contract.ShieldContract.SpendDescription; -import stest.tron.wallet.common.client.utils.TransactionUtils; @Slf4j -public class ShieldedReceiveTest extends BlockGenerate { +public class ShieldedReceiveTest extends BaseTest { - private static final String dbPath = "receive_description_test"; private static final String FROM_ADDRESS; private static final String ADDRESS_ONE_PRIVATE_KEY; private static final long OWNER_BALANCE = 100_000_000; @@ -120,16 +112,18 @@ public class ShieldedReceiveTest extends BlockGenerate { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static ConsensusService consensusService; - private static TronApplicationContext context; - private static Wallet wallet; - private static TransactionUtil transactionUtil; + @Resource + private ConsensusService consensusService; + @Resource + private Wallet wallet; + @Resource + private TransactionUtil transactionUtil; + + private static boolean init; static { + dbPath = "receive_description_test"; Args.setParam(new String[]{"--output-directory", dbPath}, "config-localtest.conf"); - context = new TronApplicationContext(DefaultConfig.class); FROM_ADDRESS = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; } @@ -137,35 +131,14 @@ public class ShieldedReceiveTest extends BlockGenerate { /** * Init data. */ - @BeforeClass - public static void init() { - FileUtil.deleteDir(new File(dbPath)); - - wallet = context.getBean(Wallet.class); - transactionUtil = context.getBean(TransactionUtil.class); - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - setManager(dbManager); - consensusService = context.getBean(ConsensusService.class); + @Before + public void init() { + if (init) { + return; + } consensusService.start(); - //give a big value for pool, avoid for chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(10_000_000_000L); - // Args.getInstance().setAllowShieldedTransaction(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } private static void librustzcashInitZksnarkParams() { diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java new file mode 100644 index 00000000000..3fe2ce02b63 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -0,0 +1,48 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import junit.framework.TestCase; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.springframework.util.Assert; +import org.tron.common.crypto.SignUtils; +import org.tron.common.crypto.sm2.SM2; +import org.tron.common.utils.ByteUtil; + +@Slf4j +public class CredentialsTest extends TestCase { + + @Test + public void testCreate() throws NoSuchAlgorithmException { + Credentials credentials = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.hasText(credentials.getAddress(),"Credentials address create failed!"); + Assert.notNull(credentials.getSignInterface(), + "Credentials cryptoEngine create failed"); + } + + @Test + public void testCreateFromSM2() { + try { + Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffff"))); + } catch (Exception e) { + Assert.isInstanceOf(IllegalArgumentException.class, e); + } + } + + @Test + public void testEquals() throws NoSuchAlgorithmException { + Credentials credentials1 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Credentials credentials2 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.isTrue(!credentials1.equals(credentials2), + "Credentials instance should be not equal!"); + Assert.isTrue(!(credentials1.hashCode() == credentials2.hashCode()), + "Credentials instance hashcode should be not equal!"); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java new file mode 100644 index 00000000000..7d584b3d8e2 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -0,0 +1,28 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import junit.framework.TestCase; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.crypto.SignUtils; +import org.tron.core.exception.CipherException; + +@Slf4j +public class WalletFileTest extends TestCase { + + + @Test + public void testGetAddress() throws NoSuchAlgorithmException, CipherException { + WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.assertTrue(!walletFile1.getAddress().equals(walletFile2.getAddress())); + Assert.assertTrue(!walletFile1.getCrypto().equals(walletFile2.getCrypto())); + Assert.assertTrue(!walletFile1.getId().equals(walletFile2.getId())); + Assert.assertTrue(walletFile1.getVersion() == walletFile2.getVersion()); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java b/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java index f87b0f81730..9f61d91a938 100755 --- a/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java +++ b/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java @@ -4,59 +4,26 @@ import com.google.protobuf.ByteString; import java.io.File; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; @Slf4j -public class AccountVoteWitnessTest { +public class AccountVoteWitnessTest extends BaseTest { - private static TronApplicationContext context; - - private static Manager dbManager; - private static MaintenanceManager maintenanceManager; - private static String dbPath = "output_witness_test"; + @Resource + private MaintenanceManager maintenanceManager; static { + dbPath = "output_witness_test"; Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * init db. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - maintenanceManager = context.getBean(MaintenanceManager.class); - // Args.setParam(new String[]{}, Constant.TEST_CONF); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * remo db when after test. - */ - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - File dbFolder = new File(dbPath); - if (deleteFolder(dbFolder)) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } private static Boolean deleteFolder(File index) { diff --git a/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java b/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java index 4549b2cde4d..e7e164e8e3b 100644 --- a/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java +++ b/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java @@ -1,19 +1,14 @@ package org.tron.program; -import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.io.File; -import java.math.BigInteger; import java.nio.file.Paths; +import java.util.concurrent.TimeUnit; + +import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; @@ -23,31 +18,22 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Utils; -import org.tron.core.Wallet; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; -import org.tron.protos.Protocol; -import org.tron.protos.contract.BalanceContract; import org.tron.tool.litefullnode.LiteFullNodeTool; -import stest.tron.wallet.common.client.utils.TransactionUtils; +@Slf4j public class LiteFullNodeToolTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private TronApplicationContext context; private WalletGrpc.WalletBlockingStub blockingStubFull = null; + private ManagedChannel channelFull; private Application appTest; - private String databaseDir; - @Rule - public ExpectedException thrown = ExpectedException.none(); - - - private static final String DB_PATH = "output_lite_fn"; + private static String dbPath = "output_lite_fn"; /** * init logic. @@ -61,16 +47,16 @@ public void startApp() { appTest.startServices(); appTest.startup(); - String fullnode = String.format("%s:%d", "127.0.0.1", - Args.getInstance().getRpcPort()); - ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); + String fullNode = String.format("%s:%d", "127.0.0.1", + Args.getInstance().getRpcPort()); + channelFull = ManagedChannelBuilder.forTarget(fullNode) + .usePlaintext() + .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } /** - * Delete the database when exit. + * Delete the database when exited. */ public static void destroy(String dbPath) { File f = new File(dbPath); @@ -84,20 +70,23 @@ public static void destroy(String dbPath) { } /** - * shutdown the fullnode. + * shutdown the fullNode. */ - public void shutdown() { + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } appTest.shutdownServices(); appTest.shutdown(); context.destroy(); } - @Before public void init() { - destroy(DB_PATH); // delete if prev failed - Args.setParam(new String[]{"-d", DB_PATH, "-w"}, "config-localtest.conf"); + destroy(dbPath); // delete if prev failed + Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-localtest.conf"); // allow account root Args.getInstance().setAllowAccountStateRoot(1); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); databaseDir = Args.getInstance().getStorage().getDbDirectory(); // init dbBackupConfig to avoid NPE Args.getInstance().dbBackupConfig = DbBackupConfig.getInstance(); @@ -105,54 +94,58 @@ public void init() { @After public void clear() { - destroy(DB_PATH); + destroy(dbPath); Args.clearParam(); + dbPath = "output_lite_fn"; } @Test - public void testToolsWithLevelDB() { + public void testToolsWithLevelDB() throws InterruptedException { logger.info("testToolsWithLevelDB start"); testTools("LEVELDB", 1); } @Test - public void testToolsWithLevelDBV2() { + public void testToolsWithLevelDBV2() throws InterruptedException { logger.info("testToolsWithLevelDB start"); testTools("LEVELDB", 2); } @Test - public void testToolsWithRocksDB() { + public void testToolsWithRocksDB() throws InterruptedException { logger.info("testToolsWithRocksDB start"); testTools("ROCKSDB", 1); } - private void testTools(String dbType, int checkpointVersion) { + private void testTools(String dbType, int checkpointVersion) + throws InterruptedException { + dbPath = String.format("%s_%s_%d", dbPath, dbType, System.currentTimeMillis()); + init(); final String[] argsForSnapshot = new String[]{"-o", "split", "-t", "snapshot", "--fn-data-path", - DB_PATH + File.separator + databaseDir, "--dataset-path", - DB_PATH}; + dbPath + File.separator + databaseDir, "--dataset-path", + dbPath}; final String[] argsForHistory = new String[]{"-o", "split", "-t", "history", "--fn-data-path", - DB_PATH + File.separator + databaseDir, "--dataset-path", - DB_PATH}; + dbPath + File.separator + databaseDir, "--dataset-path", + dbPath}; final String[] argsForMerge = - new String[]{"-o", "merge", "--fn-data-path", DB_PATH + File.separator + databaseDir, - "--dataset-path", DB_PATH + File.separator + "history"}; + new String[]{"-o", "merge", "--fn-data-path", dbPath + File.separator + databaseDir, + "--dataset-path", dbPath + File.separator + "history"}; Args.getInstance().getStorage().setDbEngine(dbType); Args.getInstance().getStorage().setCheckpointVersion(checkpointVersion); LiteFullNodeTool.setRecentBlks(3); - // start fullnode + // start fullNode startApp(); // produce transactions for 18 seconds generateSomeTransactions(18); // stop the node shutdown(); // delete tran-cache - FileUtil.deleteDir(Paths.get(DB_PATH, databaseDir, "trans-cache").toFile()); + FileUtil.deleteDir(Paths.get(dbPath, databaseDir, "trans-cache").toFile()); // generate snapshot LiteFullNodeTool.main(argsForSnapshot); - // start fullnode + // start fullNode startApp(); // produce transactions for 6 seconds generateSomeTransactions(6); @@ -161,18 +154,18 @@ private void testTools(String dbType, int checkpointVersion) { // generate history LiteFullNodeTool.main(argsForHistory); // backup original database to database_bak - File database = new File(Paths.get(DB_PATH, databaseDir).toString()); - if (!database.renameTo(new File(Paths.get(DB_PATH, databaseDir + "_bak").toString()))) { + File database = new File(Paths.get(dbPath, databaseDir).toString()); + if (!database.renameTo(new File(Paths.get(dbPath, databaseDir + "_bak").toString()))) { throw new RuntimeException( String.format("rename %s to %s failed", database.getPath(), - Paths.get(DB_PATH, databaseDir).toString())); + Paths.get(dbPath, databaseDir))); } // change snapshot to the new database - File snapshot = new File(Paths.get(DB_PATH, "snapshot").toString()); - if (!snapshot.renameTo(new File(Paths.get(DB_PATH, databaseDir).toString()))) { + File snapshot = new File(Paths.get(dbPath, "snapshot").toString()); + if (!snapshot.renameTo(new File(Paths.get(dbPath, databaseDir).toString()))) { throw new RuntimeException( String.format("rename snapshot to %s failed", - Paths.get(DB_PATH, databaseDir).toString())); + Paths.get(dbPath, databaseDir))); } // start and validate the snapshot startApp(); diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 0bd2dccfe85..422ec5e6876 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -6,8 +6,6 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.client.DatabaseGrpcClient; import org.tron.core.Constant; @@ -23,14 +21,12 @@ public class SolidityNodeTest { private static TronApplicationContext context; private static RpcApiService rpcApiService; - private static Application appT; - private static String dbPath = "output_witness_test"; + private static String dbPath = "output_sn_test"; static { Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); Args.getInstance().setSolidityNode(true); - appT = ApplicationFactory.create(context); rpcApiService = context.getBean(RpcApiService.class); } @@ -79,11 +75,11 @@ public void testSolidityArgs() { @Test public void testSolidityGrpcCall() { DatabaseGrpcClient databaseGrpcClient = null; - String addr = Args.getInstance().getTrustNodeAddr(); + String address = Args.getInstance().getTrustNodeAddr(); try { - databaseGrpcClient = new DatabaseGrpcClient(addr); + databaseGrpcClient = new DatabaseGrpcClient(address); } catch (Exception e) { - logger.error("Failed to create database grpc client {}", addr); + logger.error("Failed to create database grpc client {}", address); } Assert.assertNotNull(databaseGrpcClient); @@ -93,6 +89,14 @@ public void testSolidityGrpcCall() { Block genesisBlock = databaseGrpcClient.getBlock(0); Assert.assertNotNull(genesisBlock); Assert.assertFalse(genesisBlock.getTransactionsList().isEmpty()); + Block invalidBlock = databaseGrpcClient.getBlock(-1); + Assert.assertNotNull(invalidBlock); + try { + databaseGrpcClient = new DatabaseGrpcClient(address, -1); + } catch (Exception e) { + logger.error("Failed to create database grpc client {}", address); + } + databaseGrpcClient.shutdown(); } } diff --git a/framework/src/test/java/org/tron/program/SupplementTest.java b/framework/src/test/java/org/tron/program/SupplementTest.java new file mode 100644 index 00000000000..5655ee4a098 --- /dev/null +++ b/framework/src/test/java/org/tron/program/SupplementTest.java @@ -0,0 +1,137 @@ +package org.tron.program; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.math.BigInteger; +import javax.annotation.Resource; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.tron.common.config.DbBackupConfig; +import org.tron.common.entity.PeerInfo; +import org.tron.common.utils.CompactEncoder; +import org.tron.common.utils.JsonUtil; +import org.tron.common.utils.Value; +import org.tron.core.Constant; +import org.tron.core.capsule.StorageRowCapsule; +import org.tron.core.capsule.utils.RLP; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.services.http.HttpSelfFormatFieldName; +import org.tron.core.store.StorageRowStore; +import org.tron.keystore.WalletUtils; + +@RunWith(SpringJUnit4ClassRunner.class) +@DirtiesContext +@ContextConfiguration(classes = {DefaultConfig.class}) +public class SupplementTest { + + private static final String dbPath = "output_coverage_test"; + + @Resource + private StorageRowStore storageRowStore; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + } + + @Test + public void testGet() throws Exception { + StorageRowCapsule storageRowCapsule = storageRowStore.get(new byte[]{}); + assertNotNull(storageRowCapsule); + + DbBackupConfig dbBackupConfig = new DbBackupConfig(); + dbBackupConfig.initArgs(true, "propPath", "bak1path/", "bak2path/", 1); + + WalletUtils.generateFullNewWalletFile("123456", new File(dbPath)); + WalletUtils.generateLightNewWalletFile("123456", new File(dbPath)); + WalletUtils.getDefaultKeyDirectory(); + WalletUtils.getTestnetKeyDirectory(); + WalletUtils.getMainnetKeyDirectory(); + + Value value = new Value(new byte[]{1}); + value.asBytes(); + value = new Value(1); + value.asInt(); + value = new Value(100L); + value.asLong(); + value = new Value(new BigInteger("1000")); + value.asBigInt(); + value = new Value("1000"); + value.asString(); + value.isEmpty(); + value = new Value(new byte[]{1, 2, 3}); + value.isList(); + value.isReadableString(); + value.isHexString(); + value.isHashCode(); + value.isNull(); + value.length(); + assertNotNull(value.toString()); + value.countBranchNodes(); + + PeerInfo peerInfo = new PeerInfo(); + peerInfo.setAvgLatency(peerInfo.getAvgLatency()); + peerInfo.setBlockInPorcSize(peerInfo.getBlockInPorcSize()); + peerInfo.setConnectTime(peerInfo.getConnectTime()); + peerInfo.setDisconnectTimes(peerInfo.getDisconnectTimes()); + peerInfo.setHeadBlockTimeWeBothHave(peerInfo.getHeadBlockTimeWeBothHave()); + peerInfo.setHeadBlockWeBothHave(peerInfo.getHeadBlockWeBothHave()); + peerInfo.setHost(peerInfo.getHost()); + peerInfo.setInFlow(peerInfo.getInFlow()); + peerInfo.setLastBlockUpdateTime(peerInfo.getLastBlockUpdateTime()); + peerInfo.setLastSyncBlock(peerInfo.getLastSyncBlock()); + peerInfo.setLocalDisconnectReason(peerInfo.getLocalDisconnectReason()); + peerInfo.setNodeCount(peerInfo.getNodeCount()); + peerInfo.setNodeId(peerInfo.getNodeId()); + peerInfo.setRemainNum(peerInfo.getRemainNum()); + peerInfo.setRemoteDisconnectReason(peerInfo.getRemoteDisconnectReason()); + peerInfo.setScore(peerInfo.getScore()); + peerInfo.setPort(peerInfo.getPort()); + peerInfo.setSyncFlag(peerInfo.isSyncFlag()); + peerInfo.setNeedSyncFromPeer(peerInfo.isNeedSyncFromPeer()); + peerInfo.setNeedSyncFromUs(peerInfo.isNeedSyncFromUs()); + peerInfo.setSyncToFetchSize(peerInfo.getSyncToFetchSize()); + peerInfo.setSyncToFetchSizePeekNum(peerInfo.getSyncToFetchSizePeekNum()); + peerInfo.setSyncBlockRequestedSize(peerInfo.getSyncBlockRequestedSize()); + peerInfo.setUnFetchSynNum(peerInfo.getUnFetchSynNum()); + peerInfo.setActive(peerInfo.isActive()); + + assertNotNull(JsonUtil.json2Obj("{}", PeerInfo.class)); + assertNotNull(JsonUtil.obj2Json(peerInfo)); + + assertTrue(HttpSelfFormatFieldName.isAddressFormat( + "protocol.DelegatedResourceMessage.fromAddress")); + assertTrue(HttpSelfFormatFieldName.isNameStringFormat( + "protocol.MarketPriceList.buy_token_id")); + + CompactEncoder.packNibbles(new byte[] {1,2,3,4,5,6,7}); + assertFalse(CompactEncoder.hasTerminator(new byte[] {1,2,3,4,5,6,7})); + CompactEncoder.unpackToNibbles(new byte[] {1,2,3,4,5,6,7}); + CompactEncoder.binToNibblesNoTerminator(new byte[] {1,2,3,4,5,6,7}); + + assertNotNull(RLP.decodeIP4Bytes(new byte[] {1,2,3,4,5,6,7}, 0)); + RLP.decodeByteArray(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.nextItemLength(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decodeStringItem(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decodeInt(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decode2OneItem(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decode2(new byte[] {1,2,3,4,5,6,7}, 1); + RLP.decode2(new byte[] {1,2,3,4,5,6,7}); + thrown.expect(ClassCastException.class); + RLP.unwrapList(new byte[] {1,2,3,4,5,6,7}); + } + +} diff --git a/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java b/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java deleted file mode 100644 index 636c2d361df..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class BrokerageTest001 { - - private String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - private String dev001Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] dev001Address = PublicMethed.getFinalAddress(dev001Key); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - PublicMethed.printAddress(dev001Key); - } - - @Test - public void updateBrokerageTest001() { - // witness updateBrokerage - Assert.assertTrue(updateBrokerage(witnessAddress001, 55, blockingStubFull)); - - Assert.assertTrue(updateBrokerage(witnessAddress001, 0, blockingStubFull)); - - Assert.assertTrue(updateBrokerage(witnessAddress001, 100, blockingStubFull)); - - Assert.assertFalse(updateBrokerage(witnessAddress001, -55, blockingStubFull)); - - // normal account updateBrokerage fail - Assert.assertFalse(updateBrokerage(dev001Address, 55, blockingStubFull)); - } - - @Test - public void getBrokerageTest001() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(witnessAddress001)) - .build(); - - Assert.assertEquals(20, blockingStubFull.getBrokerageInfo(bytesMessage).getNum()); - - // getBrokerageInfo from solidity node - Assert.assertEquals(20, blockingStubSolidity.getBrokerageInfo(bytesMessage).getNum()); - Assert.assertEquals(20, blockingStubSoliInFull.getBrokerageInfo(bytesMessage).getNum()); - Assert.assertEquals(20, blockingStubPbft.getBrokerageInfo(bytesMessage).getNum()); - } - - @Test - public void getRewardTest002() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(witnessAddress001)) - .build(); - Assert.assertTrue(blockingStubFull.getRewardInfo(bytesMessage) != null); - - // getRewardInfo from solidity node - Assert.assertTrue(blockingStubSolidity.getRewardInfo(bytesMessage) != null); - Assert.assertTrue(blockingStubPbft.getRewardInfo(bytesMessage) != null); - Assert.assertTrue(blockingStubSoliInFull.getRewardInfo(bytesMessage) != null); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - boolean updateBrokerage(byte[] owner, int brokerage, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - logger.info("transaction:" + transaction); - if (transactionExtention.getResult().getResult()) { - return true; - } - return true; - } - - public void getBrokerage() { - - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java deleted file mode 100644 index 003518663d3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java +++ /dev/null @@ -1,232 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestAccount001 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String invalidTestKey = - "592BB6C9BB255409A6A45EFD18E9A74FECDDCCE93A40D96B70FBE334E6361E36"; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test - public void testqueryaccountfromfullnode() { - //Query success, get the right balance,bandwidth and the account name. - Account queryResult = queryAccount(testKey002, blockingStubFull); - /* Account queryResult = PublicMethed.queryAccountByAddress(fromAddress,blockingStubFull); - logger.info(ByteArray.toStr(queryResult.getAccountName().toByteArray())); - logger.info(Long.toString(queryResult.getBalance())); - logger.info(ByteArray.toStr(queryResult.getAddress().toByteArray()));*/ - Assert.assertTrue(queryResult.getBalance() > 0); - //Assert.assertTrue(queryResult.getBandwidth() >= 0); - Assert.assertTrue(queryResult.getAccountName().toByteArray().length > 0); - Assert.assertFalse(queryResult.getAddress().isEmpty()); - - //Query failed - Account invalidQueryResult = queryAccount(invalidTestKey, blockingStubFull); - Assert.assertTrue(invalidQueryResult.getAccountName().isEmpty()); - Assert.assertTrue(invalidQueryResult.getAddress().isEmpty()); - - //Improve coverage. - queryResult.hashCode(); - queryResult.getSerializedSize(); - queryResult.equals(queryResult); - queryResult.equals(invalidQueryResult); - } - - @Test - public void testqueryaccountfromsoliditynode() { - //Query success, get the right balance,bandwidth and the account name. - Account queryResult = solidityqueryAccount(testKey002, blockingStubSolidity); - Assert.assertTrue(queryResult.getBalance() > 0); - //Assert.assertTrue(queryResult.getBandwidth() >= 0); - Assert.assertTrue(queryResult.getAccountName().toByteArray().length > 0); - Assert.assertFalse(queryResult.getAddress().isEmpty()); - - //Query failed - Account invalidQueryResult = solidityqueryAccount(invalidTestKey, blockingStubSolidity); - Assert.assertTrue(invalidQueryResult.getAccountName().isEmpty()); - Assert.assertTrue(invalidQueryResult.getAddress().isEmpty()); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - logger.info(Integer.toString(ecKey.getAddress().length)); - - //PublicMethed.AddPreFix(); - logger.info(Integer.toString(ecKey.getAddress().length)); - System.out.println("address ====== " + ByteArray.toHexString(ecKey.getAddress())); - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - //return grpcQueryAccount(address,blockingStubFull); - } - - /** - * constructor. - */ - - public Account solidityqueryAccount(String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - //byte[] address = PublicMethed.AddPreFix(ecKey.getAddress()); - return grpcQueryAccountSolidity(ecKey.getAddress(), blockingStubSolidity); - //return grpcQueryAccountSolidity(address,blockingStubSolidity); - } - - /** - * constructor. - */ - - public String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //address = PublicMethed.AddPreFix(address); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Account grpcQueryAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - //address = PublicMethed.AddPreFix(address); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubSolidity.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java deleted file mode 100644 index b2206b426f7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java +++ /dev/null @@ -1,485 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestAccount003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue_" + Long.toString(now); - private static final long TotalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String mostLongNamePlusOneChar = "1abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey1.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static String getRandomStr(int length) { - String base = "abcdefghijklmnopqrstuvwxyz0123456789"; - int randomNum; - char randomChar; - Random random = new Random(); - StringBuffer str = new StringBuffer(); - - for (int i = 0; i < length; i++) { - randomNum = random.nextInt(base.length()); - randomChar = base.charAt(randomNum); - str.append(randomChar); - } - return str.toString(); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - PublicMethed.printAddress(lowBalTest); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void test1CreateAccount() { - Account noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - while (noCreateAccount.getBalance() != 0) { - ecKey = new ECKey(Utils.getRandom()); - lowBalAddress = ecKey.getAddress(); - lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - } - Assert.assertTrue(sendCoin(lowBalAddress, 1L, fromAddress, testKey002)); - noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - logger.info(Long.toString(noCreateAccount.getBalance())); - Assert.assertTrue(noCreateAccount.getBalance() == 1); - } - - @Test(enabled = true) - public void test2UpdateAccount() { - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, - mostLongNamePlusOneChar.getBytes(), lowBalTest, blockingStubFull)); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, "".getBytes(), lowBalTest, - blockingStubFull)); - String mostLongName = getRandomStr(33); - Assert.assertTrue(PublicMethed.updateAccount(lowBalAddress, mostLongName.getBytes(), lowBalTest, - blockingStubFull)); - String firstUpdateName = getRandomStr(32); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, firstUpdateName.getBytes(), - lowBalTest, blockingStubFull)); - String secondUpdateName = getRandomStr(15); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, secondUpdateName.getBytes(), - lowBalTest, blockingStubFull)); - } - - @Test(enabled = true) - public void test3NoBalanceCreateAssetIssue() { - Account lowaccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - if (lowaccount.getBalance() > 0) { - Assert.assertTrue(sendCoin(toAddress, lowaccount.getBalance(), lowBalAddress, lowBalTest)); - } - //Create AssetIssue failed when there is no enough balance. - Assert.assertFalse(PublicMethed.createAssetIssue(lowBalAddress, name, TotalSupply, 1, - 1, now + 100000000L, now + 10000000000L, 2, - description, url, 10000L, 10000L, 1L, - 1L, lowBalTest, blockingStubFull)); - logger.info("nobalancecreateassetissue"); - } - - @Test(enabled = true) - public void test4NoBalanceTransferTrx() { - //Send Coin failed when there is no enough balance. - Assert.assertFalse(sendCoin(toAddress, 100000000000000000L, lowBalAddress, lowBalTest)); - } - - @Test(enabled = true) - public void test5NoBalanceCreateWitness() { - //Apply to be super witness failed when no enough balance. - Assert.assertFalse(createWitness(lowBalAddress, fromAddress, lowBalTest)); - } - - @Test(enabled = true) - public void test6NoFreezeBalanceToUnfreezeBalance() { - //Unfreeze account failed when no freeze balance - Account noFreezeAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - if (noFreezeAccount.getFrozenCount() == 0) { - Assert.assertFalse(unFreezeBalance(lowBalAddress, lowBalTest)); - } else { - logger.info("This account has freeze balance, please test this case for manual"); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Boolean sendCoin(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder - = AssetIssueContractOuterClass.AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(TotalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] address, String priKey) { - //byte[] address = address; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder - = BalanceContract.UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder - = WitnessContract.VoteWitnessContract.Vote.newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - return false; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - return true; - - - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java deleted file mode 100644 index 80d84a96fa3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java +++ /dev/null @@ -1,338 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAccount004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String noFrozenBalanceTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - - private final byte[] noFrozenAddress = PublicMethed.getFinalAddress(noFrozenBalanceTestKey); - Long freezeAmount = 2000000L; - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - - } - - @Test(enabled = true) - public void testFreezeBalance() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account004AddressForFreeze = ecKey2.getAddress(); - String account004KeyForFreeze = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(account004AddressForFreeze, 10000000, - fromAddress, testKey002, blockingStubFull)); - //Freeze failed when freeze amount is large than currently balance. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 9000000000000000000L, - 3L, account004KeyForFreeze)); - //Freeze failed when freeze amount less than 1Trx - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 999999L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze duration isn't 3 days. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, 2L, testKey002)); - //Unfreeze balance failed when 3 days hasn't come. - Assert.assertFalse(PublicMethed.unFreezeBalance(account004AddressForFreeze, - account004KeyForFreeze, 0, null, blockingStubFull)); - //Freeze failed when freeze amount is 0. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 0L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze amount is -1. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, -1L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze duration is -1. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, -1L, testKey002)); - //Freeze failed when freeze duration is 0. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, 0L, testKey002)); - - } - - @Test(enabled = true) - public void testUnFreezeBalance() { - //Unfreeze failed when there is no freeze balance. - //Wait to be create account - - Assert.assertFalse(PublicMethed.unFreezeBalance(noFrozenAddress, noFrozenBalanceTestKey, 1, - null, blockingStubFull)); - logger.info("Test unfreezebalance"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account004Address = ecKey1.getAddress(); - String account004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert - .assertTrue(PublicMethed.sendcoin(account004Address, freezeAmount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(account004Address, freezeAmount, 0, - account004Key, blockingStubFull)); - Account account004; - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == 0); - Assert.assertTrue(PublicMethed.unFreezeBalance(account004Address, account004Key, 0, - null, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == freezeAmount); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account004Address, freezeAmount, 0, - 1, account004Key, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == 0); - - Assert.assertFalse(PublicMethed.unFreezeBalance(account004Address, account004Key, 0, - null, blockingStubFull)); - Assert.assertTrue(PublicMethed.unFreezeBalance(account004Address, account004Key, 1, - null, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == freezeAmount); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - PublicMethed.waitProduceNextBlock(searchBlockingStubFull); - /* while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }*/ - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java deleted file mode 100644 index da675842482..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java +++ /dev/null @@ -1,267 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAccount005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String notWitnessTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final byte[] notWitness = PublicMethed.getFinalAddress(notWitnessTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = - Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - - } - - @Test - public void testWithdrawBalance() { - //Withdraw failed when you are not witness - Assert.assertFalse(withdrawBalance(notWitness, notWitnessTestKey)); - //Due to it's hard to automation, withdraw balance success case is not automation, - // please test by manual - //Assert.assertTrue(WithdrawBalance(fromAddress,testKey002)); - //Withdraw failed when the latest time to withdraw within 1 day. - - if (withdrawBalance(fromAddress, testKey002)) { - Assert.assertFalse(withdrawBalance(fromAddress, testKey002)); - } else { - logger.info("This account has withdraw within 1 day, please confirm"); - } - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote.newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - if (key.equals(afterVote.getVotes(j).getVoteAddress())) { - Long afterVoteNum = Long.parseLong(witness.get(key)); - Assert.assertTrue(afterVoteNum == afterVote.getVotes(j).getVoteCount()); - logger.info("test equal vote"); - } - } - } - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java deleted file mode 100644 index d231ac80c60..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount006 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 20000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] account006Address = ecKey.getAddress(); - String account006Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account006Key); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void test1GetAccountNet() { - ecKey = new ECKey(Utils.getRandom()); - account006Address = ecKey.getAddress(); - account006Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //Sendcoin to this account - ByteString addressBS1 = ByteString.copyFrom(account006Address); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 100000000, 3, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(account006Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - - //Get new account net information. - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - logger.info(Long.toString(accountNetMessage.getNetLimit())); - logger.info(Long.toString(accountNetMessage.getNetUsed())); - logger.info(Long.toString(accountNetMessage.getFreeNetLimit())); - logger.info(Long.toString(accountNetMessage.getFreeNetUsed())); - logger.info(Long.toString(accountNetMessage.getTotalNetLimit())); - logger.info(Long.toString(accountNetMessage.getTotalNetWeight())); - Assert.assertTrue(accountNetMessage.getNetLimit() == 0); - Assert.assertTrue(accountNetMessage.getNetUsed() == 0); - Assert.assertTrue(accountNetMessage.getFreeNetLimit() == FREENETLIMIT); - Assert.assertTrue(accountNetMessage.getFreeNetUsed() == 0); - Assert.assertTrue(accountNetMessage.getTotalNetLimit() > 0); - Assert.assertTrue(accountNetMessage.getTotalNetWeight() > 0); - logger.info("testGetAccountNet"); - - } - - @Test(enabled = true) - public void test2UseFreeNet() { - - //Transfer some TRX to other to test free net cost. - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, - account006Key, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - //Every transaction may cost 200 net. - Assert.assertTrue(accountNetMessage.getFreeNetUsed() > 0 && accountNetMessage - .getFreeNetUsed() < 300); - logger.info("testUseFreeNet"); - } - - @Test(enabled = true) - public void test3UseMoneyToDoTransaction() { - Assert.assertTrue(PublicMethed.sendcoin(account006Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - //Use out the free net - Integer times = 0; - while (accountNetMessage.getFreeNetUsed() < BASELINE && times++ < 30) { - PublicMethed.sendcoin(fromAddress, 1L, account006Address, account006Key, - blockingStubFull); - accountNetMessage = blockingStubFull.getAccountNet(request); - } - - Account queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long beforeSendBalance = queryAccount.getBalance(); - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, account006Key, - blockingStubFull)); - queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long afterSendBalance = queryAccount.getBalance(); - //when the free net is not enough and no balance freeze, use money to do the transaction. - Assert.assertTrue(beforeSendBalance - afterSendBalance > 1); - logger.info("testUseMoneyToDoTransaction"); - } - - @Test(enabled = true) - public void test4UseNet() { - //Freeze balance to own net. - Assert.assertTrue(PublicMethed.freezeBalance(account006Address, 10000000L, - 3, account006Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1L, account006Address, - account006Key, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - Assert.assertTrue(accountNetMessage.getNetLimit() > 0); - Assert.assertTrue(accountNetMessage.getNetUsed() > 150); - - Account queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long beforeSendBalance = queryAccount.getBalance(); - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, - account006Key, blockingStubFull)); - queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long afterSendBalance = queryAccount.getBalance(); - //when you freeze balance and has net,you didn't cost money. - logger.info("before is " + Long.toString(beforeSendBalance) + " and after is " - + Long.toString(afterSendBalance)); - Assert.assertTrue(beforeSendBalance - afterSendBalance == 1); - addressBs = ByteString.copyFrom(account006Address); - request = Account.newBuilder().setAddress(addressBs).build(); - accountNetMessage = blockingStubFull.getAccountNet(request); - //when you freeze balance and has net,you cost net. - logger.info(Long.toString(accountNetMessage.getNetUsed())); - Assert.assertTrue(accountNetMessage.getNetUsed() > 350); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java deleted file mode 100644 index 33a20804976..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java +++ /dev/null @@ -1,126 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount007 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //owner account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account007Address = ecKey1.getAddress(); - String account007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //Wait to be create account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(account007Key); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testCreateAccount() { - Assert.assertTrue(PublicMethed.sendcoin(account007Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - Account accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - final Long beforeBalance = accountInfo.getBalance(); - - AccountNetMessage accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - final Long beforeFreeNet = accountNetInfo.getFreeNetUsed(); - - Assert.assertTrue(PublicMethed.createAccount(account007Address, newAccountAddress, - account007Key, blockingStubFull)); - - accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - Long afterBalance = accountInfo.getBalance(); - - accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - Long afterFreeNet = accountNetInfo.getFreeNetUsed(); - - logger.info(Long.toString(beforeBalance)); - logger.info(Long.toString(afterBalance)); - - //When creator has no bandwidth, he can't use the free net. - Assert.assertTrue(afterFreeNet == beforeFreeNet); - - //When the creator has no bandwidth, create a new account should spend 0.1TRX. - Assert.assertTrue(beforeBalance - afterBalance == 100000); - } - - @Test(enabled = true) - public void testExceptionCreateAccount() { - //Try to create an exist account - Assert - .assertFalse(PublicMethed.createAccount(account007Address, account007Address, account007Key, - blockingStubFull)); - - //Try to create an invalid account - byte[] wrongAddress = "wrongAddress".getBytes(); - Assert.assertFalse(PublicMethed.createAccount(account007Address, wrongAddress, account007Key, - blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java deleted file mode 100644 index d60c9171507..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount009 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account009Address = ecKey1.getAddress(); - String account009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account009SecondAddress = ecKey2.getAddress(); - String account009SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] account009InvalidAddress = ecKey3.getAddress(); - String account009InvalidKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account009Key); - PublicMethed.printAddress(account009SecondKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testGetEnergy() { - Assert.assertTrue(PublicMethed.sendcoin(account009Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account009SecondAddress, 10000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account009InvalidAddress, 10000000, - fromAddress, testKey002, blockingStubFull)); - - Account account009Info = PublicMethed.queryAccount(account009Key, blockingStubFull); - logger.info(Long.toString( - account009Info.getAccountResource().getFrozenBalanceForEnergy().getExpireTime())); - Assert.assertTrue(account009Info.getAccountResource().getEnergyUsage() == 0); - Assert.assertTrue(account009Info.getAccountResource().getFrozenBalanceForEnergy() - .getExpireTime() == 0); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account009Address, 1000000L, - 3, 1, account009Key, blockingStubFull)); - account009Info = PublicMethed.queryAccount(account009Key, blockingStubFull); - Assert.assertTrue(account009Info.getAccountResource().getEnergyUsage() == 0); - Assert.assertTrue(account009Info.getAccountResource().getFrozenBalanceForEnergy() - .getFrozenBalance() == 1000000L); - - AccountResourceMessage account009Resource = PublicMethed.getAccountResource(account009Address, - blockingStubFull); - Assert.assertTrue(account009Resource.getTotalEnergyLimit() >= 50000000000L); - Assert.assertTrue(account009Resource.getEnergyLimit() > 0); - Assert.assertTrue(account009Resource.getTotalEnergyWeight() >= 1); - } - - @Test(enabled = true) - public void testGetEnergyInvalid() { - //The resourceCode can only be 0 or 1 - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, - 1000000L, 3, 0, account009InvalidKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, 1000000L, - 3, -1, account009InvalidKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, 1000000L, - 3, 3, account009InvalidKey, blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java deleted file mode 100644 index 8d829424643..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java +++ /dev/null @@ -1,76 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account011Address = ecKey1.getAddress(); - String account011Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account011Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - - } - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java deleted file mode 100644 index c226cef843f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestBlock003 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetNextMaintenanceTime() { - long now = System.currentTimeMillis(); - NumberMessage getNextMaintenanceTime = blockingStubFull - .getNextMaintenanceTime(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(getNextMaintenanceTime.getNum())); - logger.info(Long.toString(now)); - Assert.assertTrue(getNextMaintenanceTime.getNum() > now); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java deleted file mode 100644 index 2a21a4bdc6d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestBlock004 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLimitNext() { - // - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(2); - builder.setEndNum(4); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.isPresent()); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 2); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).hasBlockHeader()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionLimitNext() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - //From -1 to 1 - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(-1); - builder.setEndNum(1); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 3 to 3 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(3); - builder.setEndNum(3); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 4 to 2 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(4); - builder.setEndNum(2); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 999999990 to 999999999 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(999999990); - builder.setEndNum(999999999); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java deleted file mode 100644 index 4179fd4748a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestBlock005 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLatestNum() { - // - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(3).build(); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.isPresent()); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 3); - Assert.assertTrue(getBlockByLatestNum.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue( - getBlockByLatestNum.get().getBlock(1).getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse( - getBlockByLatestNum.get().getBlock(2).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - logger.info("TestGetBlockByLatestNum ok!!!"); - - } - - @Test(enabled = true) - public void testGetBlockByExceptionNum() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(-1).build(); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - numberMessage = NumberMessage.newBuilder().setNum(0).build(); - blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - numberMessage = NumberMessage.newBuilder().setNum(100).build(); - blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java deleted file mode 100644 index 4fb4103a537..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java +++ /dev/null @@ -1,111 +0,0 @@ -package stest.tron.wallet.block; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class WalletTestBlock006 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetTransactionCountByBlockNumFromFullnode() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - Long transactionNumInBlock = 0L; - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock >= 1); - - builder.setNum(-10); - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - builder.setNum(currentBlockNum + 10000L); - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - } - - @Test(enabled = true) - public void testGetTransactionCountByBlockNumFromSolidity() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - Long transactionNumInBlock = 0L; - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock >= 1); - - builder.setNum(-10); - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - builder.setNum(currentBlockNum + 10000L); - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java deleted file mode 100644 index 3116598bc08..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java +++ /dev/null @@ -1,131 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee001 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //Witness 47.93.9.236 - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test - public void testListProposals() { - //List proposals - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer beforeProposalCount = listProposals.get().getProposalsCount(); - - //CreateProposal - final long now = System.currentTimeMillis(); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 1000000L); - PublicMethed.createProposal(witness001Address, witnessKey001, proposalMap, blockingStubFull); - - //List proposals - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Integer afterProposalCount = listProposals.get().getProposalsCount(); - Assert.assertTrue(beforeProposalCount + 1 == afterProposalCount); - logger.info(Long.toString(listProposals.get().getProposals(0).getCreateTime())); - logger.info(Long.toString(now)); - //Assert.assertTrue(listProposals.get().getProposals(0).getCreateTime() >= now); - Assert.assertTrue(listProposals.get().getProposals(0).getParametersMap().equals(proposalMap)); - - //getProposalListPaginated - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(1); - ProposalList paginatedProposalList = blockingStubFull - .getPaginatedProposalList(pageMessageBuilder.build()); - Assert.assertTrue(paginatedProposalList.getProposalsCount() >= 1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java deleted file mode 100644 index 4abd87f3937..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java +++ /dev/null @@ -1,365 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee002 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - //Witness 47.93.9.236 - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - } - - - @Test(enabled = true) - public void testCreateProposalMaintenanceTimeInterval() { - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, 10000000L, - toAddress, testKey003, blockingStubFull)); - - //0:MAINTENANCE_TIME_INTERVAL,[3*27s,24h] - //Minimum interval - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum interval - proposalMap.put(0L, 86400000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum -1 interval, create failed. - proposalMap.put(0L, 80000L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 interval - proposalMap.put(0L, 86401000L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(0L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, proposalMap, - blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateProposalAccountUpgradeCost() { - //1:ACCOUNT_UPGRADE_COST,[0,100 000 000 000 000 000]//drop - //Minimum AccountUpgradeCost - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum AccountUpgradeCost - proposalMap.put(1L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 AccountUpgradeCost - proposalMap.put(1L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 AccountUpgradeCost - proposalMap.put(1L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(1L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateProposalCreateAccountFee() { - //2:CREATE_ACCOUNT_FEE,[0,100 000 000 000 000 000]//drop - //Minimum CreateAccountFee - HashMap proposalMap = new HashMap(); - proposalMap.put(2L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum CreateAccountFee - proposalMap.put(2L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 CreateAccountFee - proposalMap.put(2L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 CreateAccountFee - proposalMap.put(2L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(2L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testTransactionFee() { - //3:TRANSACTION_FEE,[0,100 000 000 000 000 000]//drop - //Minimum TransactionFee - HashMap proposalMap = new HashMap(); - proposalMap.put(3L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum TransactionFee - proposalMap.put(3L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 TransactionFee - proposalMap.put(3L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 TransactionFee - proposalMap.put(3L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(3L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testAssetIssueFee() { - //4:ASSET_ISSUE_FEE,[0,100 000 000 000 000 000]//drop - //Minimum AssetIssueFee - HashMap proposalMap = new HashMap(); - proposalMap.put(4L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Duplicat proposals - proposalMap.put(4L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum AssetIssueFee - proposalMap.put(4L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 AssetIssueFee - proposalMap.put(4L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 AssetIssueFee - proposalMap.put(4L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(4L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testWitnessPayPerBlock() { - //5:WITNESS_PAY_PER_BLOCK,[0,100 000 000 000 000 000]//drop - //Minimum WitnessPayPerBlock - HashMap proposalMap = new HashMap(); - proposalMap.put(5L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessPayPerBlock - proposalMap.put(5L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessPayPerBlock - proposalMap.put(5L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessPayPerBlock - proposalMap.put(5L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(5L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testWitnessStandbyAllowance() { - //6:WITNESS_STANDBY_ALLOWANCE,[0,100 000 000 000 000 000]//drop - //Minimum WitnessStandbyAllowance - HashMap proposalMap = new HashMap(); - proposalMap.put(6L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessStandbyAllowance - proposalMap.put(6L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(6L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testCreateNewAccountFeeInSystemControl() { - //7:CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT,0 or 1 - HashMap proposalMap = new HashMap(); - proposalMap.put(7L, 1L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessStandbyAllowance - proposalMap.put(7L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessStandbyAllowance - proposalMap.put(6L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(6L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - - @Test(enabled = true) - public void testInvalidProposals() { - // The index isn't from 0-9 - HashMap proposalMap = new HashMap(); - proposalMap.put(10L, 60L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //The index is -1 - proposalMap.put(-1L, 6L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java deleted file mode 100644 index 12b098f95fa..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java +++ /dev/null @@ -1,166 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee003 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - //private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - //private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - //private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testApproveProposal() { - PublicMethed.sendcoin(witness001Address, 1000000L, - toAddress, testKey003, blockingStubFull); - PublicMethed.sendcoin(witness002Address, 1000000L, - toAddress, testKey003, blockingStubFull); - - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list after approve - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - logger.info(Integer.toString(listProposals.get().getProposals(0).getApprovalsCount())); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 1); - //logger.info(Base58.encode58Check(witness002Address)); - //logger.info(Base58.encode58Check(listProposals.get().getProposals(0). - // getApprovalsList().get(0).toByteArray())); - Assert.assertTrue(Base58.encode58Check(witness002Address).equals(Base58.encode58Check( - listProposals.get().getProposals(0).getApprovalsList().get(0).toByteArray()))); - - //Failed to approve proposal when you already approval this proposal - Assert.assertFalse(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - - //Success to change the option from true to false. - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - false, blockingStubFull)); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 0); - - //Failed to approvel proposal when you already approval this proposal - Assert.assertFalse(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - false, blockingStubFull)); - - //Non witness can't approval proposal - Assert.assertFalse(PublicMethed.approveProposal(toAddress, testKey003, proposalId, - true, blockingStubFull)); - - //Muti approval - Assert.assertTrue(PublicMethed.approveProposal(witness001Address, witnessKey001, proposalId, - true, blockingStubFull)); - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness003Address,witnessKey003,proposalId, - // true,blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness004Address,witnessKey004,proposalId, - // true,blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness005Address,witnessKey005,proposalId, - // true,blockingStubFull)); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 2); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java deleted file mode 100644 index 6112ab62c7c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java +++ /dev/null @@ -1,219 +0,0 @@ -package stest.tron.wallet.committee; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Proposal; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee004 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - //private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - //private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - //private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void test1DeleteProposal() { - PublicMethed.sendcoin(witness001Address, 1000000L, - toAddress, testKey003, blockingStubFull); - PublicMethed.sendcoin(witness002Address, 1000000L, - toAddress, testKey003, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create a proposal and approval it - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 99999L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - Assert.assertTrue(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, true, blockingStubFull)); - logger.info(Integer.toString(listProposals.get().getProposals(0).getStateValue())); - //The state is "pending", state value == 0 - Assert.assertTrue(listProposals.get().getProposals(0).getStateValue() == 0); - - //When the proposal isn't created by you, you can't delete it. - Assert.assertFalse(PublicMethed.deleteProposal(witness002Address, witnessKey002, - proposalId, blockingStubFull)); - //Cancel the proposal - Assert.assertTrue(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId, blockingStubFull)); - //When the state is cancel, you can't delete it again. - Assert.assertFalse(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId, blockingStubFull)); - //You can't delete an invalid proposal - Assert.assertFalse(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId + 100, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - logger.info(Integer.toString(listProposals.get().getProposals(0).getStateValue())); - //The state is "cancel", state value == 3 - Assert.assertTrue(listProposals.get().getProposals(0).getStateValue() == 3); - - //When the state is cancel, you can't approval proposal - Assert.assertFalse(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, true, blockingStubFull)); - Assert.assertFalse(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, false, blockingStubFull)); - } - - @Test(enabled = true) - public void test2GetProposal() { - //Create a proposal and approval it - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 999999999L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - - BytesMessage request = BytesMessage.newBuilder().setValue(ByteString.copyFrom( - ByteArray.fromLong(Long.parseLong(proposalId.toString())))) - .build(); - Proposal proposal = blockingStubFull.getProposalById(request); - Optional getProposal = Optional.ofNullable(proposal); - - Assert.assertTrue(getProposal.isPresent()); - Assert.assertTrue(getProposal.get().getStateValue() == 0); - - //Invalid get proposal - final Integer wrongProposalId = proposalId + 99; - request = BytesMessage.newBuilder().setValue(ByteString.copyFrom( - ByteArray.fromLong(Long.parseLong(wrongProposalId.toString())))) - .build(); - proposal = blockingStubFull.getProposalById(request); - getProposal = Optional.ofNullable(proposal); - logger.info(Long.toString(getProposal.get().getCreateTime())); - Assert.assertTrue(getProposal.get().getCreateTime() == 0); - } - - @Test(enabled = false) - public void testGetChainParameters() { - //Set the default map - HashMap defaultCommitteeMap = new HashMap(); - defaultCommitteeMap.put("MAINTENANCE_TIME_INTERVAL", 300000L); - defaultCommitteeMap.put("ACCOUNT_UPGRADE_COST", 9999000000L); - defaultCommitteeMap.put("CREATE_ACCOUNT_FEE", 100000L); - defaultCommitteeMap.put("TRANSACTION_FEE", 10L); - defaultCommitteeMap.put("ASSET_ISSUE_FEE", 1024000000L); - defaultCommitteeMap.put("WITNESS_PAY_PER_BLOCK", 32000000L); - defaultCommitteeMap.put("WITNESS_STANDBY_ALLOWANCE", 115200000000L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT", 0L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_BANDWIDTH_RATE", 1L); - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - } - Assert.assertTrue(getChainParameters.get().getChainParameterCount() >= 10); - Assert.assertTrue(getChainParameters.get() - .getChainParameter(1).getValue() == 9999000000L); - Assert.assertTrue(getChainParameters.get().getChainParameter(4) - .getValue() == 1024000000L); - Assert.assertTrue(getChainParameters.get().getChainParameter(7).getValue() == 0); - Assert.assertTrue(getChainParameters.get().getChainParameter(8).getValue() == 1); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java deleted file mode 100644 index a0164c6bba6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java +++ /dev/null @@ -1,19 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -/** - * Cipher exception wrapper. - */ -public class CipherException extends Exception { - - public CipherException(String message) { - super(message); - } - - public CipherException(Throwable cause) { - super(cause); - } - - public CipherException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java deleted file mode 100644 index ec4b061d1b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.TestListenerAdapter; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; - -public class DailyBuildReport extends TestListenerAdapter { - - StringBuilder passedDescriptionList = new StringBuilder(""); - StringBuilder failedDescriptionList = new StringBuilder(""); - StringBuilder skippedDescriptionList = new StringBuilder(""); - private Integer passedNum = 0; - private Integer failedNum = 0; - private Integer skippedNum = 0; - private String reportPath; - public Map transactionType = new HashMap<>(); - public Long endBlockNum = 0L; - public static Long startBlockNum = 0L; - public Long totalTransactionNum = 0L; - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - @Override - public void onStart(ITestContext context) { - reportPath = "Daily_Build_Report"; - StringBuilder sb = new StringBuilder("3.Stest report: "); - String res = sb.toString(); - try { - Files.write((Paths.get(reportPath)), res.getBytes("utf-8")); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void onTestSuccess(ITestResult result) { - passedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - passedNum++; - } - - @Override - public void onTestFailure(ITestResult result) { - failedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - failedNum++; - } - - @Override - public void onTestSkipped(ITestResult result) { - skippedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - skippedNum++; - } - - - @Override - public void onFinish(ITestContext testContext) { - StringBuilder sb = new StringBuilder(); - sb.append("Total: " + (passedNum + failedNum + skippedNum) + ", " + "Passed: " + passedNum - + ", " + "Failed: " + failedNum + ", " + "Skipped: " + skippedNum + "\n"); - sb.append("------------------------------------------------------------------------------\n"); - List> list = calculateAfterDailyBuild(); - sb.append("Total transaction number:" + totalTransactionNum + "\n"); - sb.append("Transaction type list:" + "\n"); - for (Map.Entry entry : list) { - sb.append(entry.getKey()); - for (int i = entry.getKey().length(); i < 40; i++) { - sb.append(" "); - } - sb.append(" : " + entry.getValue() + "\n"); - - } - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Passed list " + "\n"); - //sb.append("Passed case List: " + "\n"); - sb.append(passedDescriptionList.toString()); - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Failed list: " + "\n"); - //sb.append("Failed case List: " + "\n"); - sb.append(failedDescriptionList.toString()); - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Skipped list: " + "\n"); - //sb.append("Skipped case List: " + "\n"); - sb.append(skippedDescriptionList.toString()); - sb.append("----------------------------------------------------------------\n"); - - String res = sb.toString(); - try { - Files.write((Paths.get(reportPath)), res.getBytes("utf-8"), StandardOpenOption.APPEND); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /** - * calculate transaction num and transaction type After DailyBuild. - */ - public List> calculateAfterDailyBuild() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - endBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - System.out.println("-----startnum :" + startBlockNum + "-----endnum:" + endBlockNum); - List listTrans; - List listContract; - Protocol.Block block; - int transNum; - int contractNum; - String contractType; - for (long i = startBlockNum; i < endBlockNum; i++) { - block = PublicMethed.getBlock(i, blockingStubFull); - listTrans = block.getTransactionsList(); - transNum = block.getTransactionsCount(); - totalTransactionNum += transNum; - for (int j = 0; j < transNum; j++) { - listContract = listTrans.get(j).getRawData().getContractList(); - contractNum = listContract.size(); - for (int k = 0; k < contractNum; k++) { - contractType = listContract.get(k).getType().toString(); - transactionType.put(contractType, transactionType.getOrDefault(contractType, 0) + 1); - } - } - } - try { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - - List> list = new ArrayList<>(transactionType.entrySet()); - Collections.sort(list, new Comparator>() { - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - return (o2.getValue()).compareTo(o1.getValue()); - } - }); - return list; - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java deleted file mode 100644 index 03268fa8b9e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.List; - -public class FileUtil { - - /** - * constructor. - */ - - public static List recursiveList(String path) throws IOException { - - final List files = new ArrayList<>(); - - Files.walkFileTree(Paths.get(path), new FileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - files.add(file.toString()); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) { - return FileVisitResult.CONTINUE; - } - }); - - return files; - } - - /** - * constructor. - */ - - public static boolean recursiveDelete(String fileName) { - File file = new File(fileName); - if (file.exists()) { - //check if the file is a directory - if (file.isDirectory()) { - if ((file.list()).length > 0) { - for (String s : file.list()) { - //call deletion of file individually - recursiveDelete(fileName + System.getProperty("file.separator") + s); - } - } - } - - file.setWritable(true); - boolean result = file.delete(); - return result; - } else { - return false; - } - } - - /** - * constructor. - */ - - public static void saveData(String filePath, byte[] data) { - FileOutputStream fos = null; - try { - File file = new File(filePath); - file.createNewFile(); - fos = new FileOutputStream(file); - fos.write(data); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - /** - * constructor. - */ - - public static byte[] readData(String filePath) { - FileInputStream fi = null; - try { - File file = new File(filePath); - long fileSize = file.length(); - if (fileSize > Integer.MAX_VALUE) { - System.out.println("file too big..."); - return null; - } - fi = new FileInputStream(file); - byte[] buffer = new byte[(int) fileSize]; - int offset = 0; - int numRead; - while (offset < buffer.length - && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { - offset += numRead; - } - if (offset != buffer.length) { - return null; - } - return buffer; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fi != null) { - try { - fi.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return null; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java deleted file mode 100644 index eec885184d4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ /dev/null @@ -1,405 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -// import java.util.*; - -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.Util; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class JsonRpcBase { - - public final String foundationAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - - public static final String jsonRpcOwnerKey = - Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); - public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); - public static final String jsonRpcOwnerAddressString = - PublicMethed.getAddressString(jsonRpcOwnerKey); - public static String jsonRpcNode = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); - public static String jsonRpcNodeForSolidity = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); - public static String httpFullNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - public static String httpsolidityNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(3); - public static String ethHttpsNode = - Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public static String data = null; - public String paramString = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - public String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - public static String trc20AddressByteString; - public static String trc20AddressHex; - public static String contractAddressFrom58; - public static String contractTrc20AddressFrom58; - public static String contractAddressFromHex; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = - "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - public static String name = "jsonrpc-test"; - public static String jsonRpcAssetId; - public static Integer blockNum; - public static Integer blockNumForTrc20; - public static String blockNumHex; - public static String blockId; - public static String txid; - public static String trc20Txid; - - /** constructor. */ - @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") - public void deployJsonRpcUseResource() throws Exception { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // Create a new Asset Issue - Assert.assertTrue( - PublicMethed.createAssetIssue( - jsonRpcOwnerAddress, - name, - totalSupply, - 1, - 1, - System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, - 1, - "description", - "urlurlurl", - 2000L, - 2000L, - 1L, - 1L, - jsonRpcOwnerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - jsonRpcAssetId = responseContent.getString("asset_issued_ID"); - - deployContract(); - triggerContract(); - deployTrc20Contract(); - } - - /** constructor. */ - public void deployContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("name", "transferTokenContract"); - param.addProperty("gas", "0x245498"); - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - System.out.println("CODE:" + code); - String abi = retMap.get("abI").toString(); - System.out.println("abi:" + abi); - - param.addProperty("abi", abi); - param.addProperty("data", code); - param.addProperty("consumeUserResourcePercent", 100); - param.addProperty("originEnergyLimit", 11111111111111L); - param.addProperty("value", "0x1f4"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - - responseContent = HttpMethed.parseStringContent(transactionString); - final String txid = responseContent.getString("txID"); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); - - response = HttpMethed.getTransactionById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractAddressFrom58:" + contractAddressFrom58); - } - - /** constructor. */ - public void triggerContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - - String tokenIdParam = - "00000000000000000000000000000000000000000000000000000000000" - + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - paramString = addressParam + tokenIdParam + tokenValueParam; - logger.info("paramString:" + paramString); - - String selector = "TransferTokenTo(address,trcToken,uint256)"; - // exit(1); - param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); - data = "0x" + Util.parseMethod(selector, paramString); - param.addProperty("gas", "0x245498"); - param.addProperty("value", "0x1389"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - logger.info("transactionString : " + transactionString); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - logger.info("transactionSignString:" + transactionSignString); - responseContent = HttpMethed.parseStringContent(transactionString); - txid = responseContent.getString("txID"); - logger.info("triggerTxid:" + txid); - - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - logger.info("response:" + response); - HttpMethed.verificationResult(response); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); - org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); - - blockNum = - (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - blockId = responseContent.get("blockID").toString(); - } - - /** constructor. */ - public void deployTrc20Contract() throws InterruptedException { - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployTrc20Txid = - PublicMethed.deployContractWithConstantParame( - contractName, - abi, - code, - constructorStr, - data, - "", - maxFeeLimit, - 0L, - 100, - null, - jsonRpcOwnerKey, - jsonRpcOwnerAddress, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("deployTrc20Txid:" + deployTrc20Txid); - response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractTrc20AddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - - // NewFilterId = createNewFilterId(); - - Optional infoById = - PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); - - trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); - byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); - - String selector = "transfer(address,uint256)"; - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String paramString = addressParam + transferValueParam; - trc20Txid = - PublicMethed.triggerContract( - trc20Address, - selector, - paramString, - true, - 0, - maxFeeLimit, - "0", - 0, - jsonRpcOwnerAddress, - jsonRpcOwnerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - blockNumForTrc20 = - (int) - (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) - .get() - .getBlockNumber()); - } - - /** constructor. */ - public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method) { - return getJsonRpcBody(method, new JsonArray(), 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params) { - return getJsonRpcBody(method, params, 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("jsonrpc", "2.0"); - jsonObject.addProperty("method", method); - jsonObject.add("params", params); - jsonObject.addProperty("id", id); - - return jsonObject; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java deleted file mode 100644 index e528c647545..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ /dev/null @@ -1,7091 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import static org.tron.common.crypto.Hash.sha3; -import static org.tron.common.crypto.Hash.sha3omit12; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.common.primitives.Longs; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.netty.util.internal.StringUtil; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.DecryptNotesMarked; -import org.tron.api.GrpcAPI.DelegatedResourceList; -import org.tron.api.GrpcAPI.DelegatedResourceMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.IvkDecryptAndMarkParameters; -import org.tron.api.GrpcAPI.IvkDecryptParameters; -import org.tron.api.GrpcAPI.NfParameters; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.OvkDecryptParameters; -import org.tron.api.GrpcAPI.PrivateParameters; -import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk; -import org.tron.api.GrpcAPI.ReceiveNote; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.SpendAuthSigParameters; -import org.tron.api.GrpcAPI.SpendNote; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionApprovedList; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletGrpc.WalletBlockingStub; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.capsule.BlockCapsule.BlockId; -import org.tron.core.zen.address.DiversifierT; -import org.tron.core.zen.address.ExpandedSpendingKey; -import org.tron.core.zen.address.FullViewingKey; -import org.tron.core.zen.address.IncomingViewingKey; -import org.tron.core.zen.address.PaymentAddress; -import org.tron.core.zen.address.SpendingKey; -import org.tron.keystore.WalletFile; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.Key; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.Transaction.Result; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AccountContract.SetAccountIdContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; -import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; -import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract; -import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract; -import org.tron.protos.contract.MarketContract; -import org.tron.protos.contract.ProposalContract.ProposalApproveContract; -import org.tron.protos.contract.ProposalContract.ProposalCreateContract; -import org.tron.protos.contract.ProposalContract.ProposalDeleteContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; -import org.tron.protos.contract.ShieldContract.SpendDescription; -import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract.Builder; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; -import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; -import org.tron.protos.contract.StorageContract.BuyStorageContract; -import org.tron.protos.contract.StorageContract.SellStorageContract; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; - -public class PublicMethed { - - // Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - private static final String FilePath = "Wallet"; - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - // private WalletGrpc.WalletBlockingStub blockingStubFull = null; - // private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public static Map utxoMapNote = new ConcurrentHashMap(); - public static List spendUtxoList = new ArrayList<>(); - private static List walletFile = new ArrayList<>(); - private static ShieldWrapper shieldWrapper = new ShieldWrapper(); - Wallet wallet = new Wallet(); - public static volatile Integer witnessNum; - - /** constructor. */ - public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { - if (null == witnessNum) { - witnessNum = PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList().size(); - } - - return witnessNum; - } - - /** constructor. */ - public static String createAssetIssueGetTxid( - byte[] address, - String name, - String abbreviation, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - String abbreviation, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - int precision, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setPrecision(precision); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Return createAssetIssue2( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - // builder.setPublicFreeAssetNetUsage(); - // builder.setPublicLatestFreeNetTime(); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = - blockingStubFull.createAssetIssue2(builder.build()); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return ret; - } catch (Exception ex) { - ex.printStackTrace(); - // return false; - return Return.getDefaultInstance(); - } - } - - /** constructor. */ - public static Account queryAccountByAddress( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Account queryAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Protocol.Account queryAccount( - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); // 04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - /** constructor. */ - public static Account queryAccount( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Account getAccountById( - String accountId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } - - /** constructor. */ - public static Account getAccountByIdFromSolidity( - String accountId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } - - /** constructor. */ - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** constructor. */ - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - return ecKey.getAddress(); - } - - /** constructor. */ - public static Protocol.Account grpcQueryAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Protocol.Block getBlock( - long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - /** constructor. */ - public static BlockExtention getBlock2(long blockNum, WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - } - - /** constructor. */ - public static Protocol.Transaction signTransaction( - ECKey ecKey, Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - // logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - logger.info( - "Txid in sign is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } - - /** constructor. */ - public static Protocol.Transaction signTransactionForShield( - ECKey ecKey, Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - // logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - logger.info( - "Txid in sign is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } - - /** constructor. */ - public static boolean participateAssetIssue( - byte[] to, - byte[] assertName, - long amount, - byte[] from, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return participateAssetIssue2( - byte[] to, - byte[] assertName, - long amount, - byte[] from, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - // Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - return ret; - } - } - - /** constructor. */ - public static Boolean freezeBalance( - byte[] addRess, - long freezeBalance, - long freezeDuration, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - // Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - // beforeBandwidth = beforeFronzen.getBandwidth(); - // logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - /* Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info("beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" - + afterFrozenBalance.toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance);*/ - } - - /** constructor. */ - public static Return freezeBalance2( - byte[] addRess, - long freezeBalance, - long freezeDuration, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - // Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - // beforeBandwidth = beforeFronzen.getBandwidth(); - // logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - if (response.getResult() == false) { - return response; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info( - "beforefronen" - + beforeFrozenBalance.toString() - + " afterfronzen" - + afterFrozenBalance.toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - return ret; - } - - /** constructor. */ - public static Boolean unFreezeBalance( - byte[] address, - String priKey, - int resourceCode, - byte[] receiverAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Boolean sendcoin( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - while (times++ <= 2) { - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - continue; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - return false; - } - - /** constructor. */ - public static String sendcoinGetTransactionHex( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "HEX transaction is : " - + "transaction hex string is " - + ByteArray.toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - } - - /** constructor. */ - public static Boolean cancelDeferredTransactionById( - String txid, byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - /*Contract.CancelDeferredTransactionContract.Builder builder = Contract - .CancelDeferredTransactionContract.newBuilder(); - builder.setTransactionId(ByteString.copyFrom(ByteArray.fromHexString(txid))); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - Contract.CancelDeferredTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .createCancelDeferredTransactionContract(contract); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Cancel transaction before sign txid = " + ByteArray.toHexString( - transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - System.out.println( - "Cancel transaction txid = " + ByteArray.toHexString(transactionExtention - .getTxid().toByteArray())); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult();*/ - return null; - } - - - - /** constructor. */ - public static Boolean sendcoinDelayed( - byte[] to, - long amount, - long delaySeconds, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - - // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "Txid is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** constructor. */ - public static String sendcoinDelayedGetTxid( - byte[] to, - long amount, - long delaySeconds, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - - // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "Txid is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - - - - /** constructor. */ - public static Return sendcoin2( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static String sendcoinGetTransactionId( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - // Test raw data - /* Protocol.Transaction.raw.Builder builder1 = transaction.getRawData().toBuilder(); - builder1.setData(ByteString.copyFromUtf8("12345678")); - Transaction.Builder builder2 = transaction.toBuilder(); - builder2.setRawData(builder1); - transaction = builder2.build();*/ - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Optional getTransactionById( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static Optional getTransactionById( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static Long getAssetBalanceByAssetId( - ByteString assetId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); - Long assetOwnerAssetBalance = 0L; - for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { - if (assetId.toStringUtf8().equalsIgnoreCase(id)) { - assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); - } - } - logger.info("asset balance is " + assetOwnerAssetBalance); - return assetOwnerAssetBalance; - } - - /* - public static Optional getDeferredTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - DeferredTransaction transaction = blockingStubFull.getDeferredTransactionById(request); - if (Objects.isNull(transaction)) { - transaction = blockingStubFull.getDeferredTransactionById(request); - } - return Optional.ofNullable(transaction); - } - */ - - /** constructor. */ - public static Optional getTransactionByIdSolidity( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubSolidity.getTransactionById(request); - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static String printTransaction(Transaction transaction) { - String result = ""; - result += "hash: "; - result += "\n"; - result += - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); - result += "\n"; - result += "txid: "; - result += "\n"; - result += - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - result += "\n"; - - if (transaction.getRawData() != null) { - result += "raw_data: "; - result += "\n"; - result += "{"; - result += "\n"; - result += printTransactionRow(transaction.getRawData()); - result += "}"; - result += "\n"; - } - - return result; - } - - /** constructor. */ - public static long printTransactionRow(Transaction.raw raw) { - long timestamp = raw.getTimestamp(); - - return timestamp; - } - - /** constructor. */ - public static boolean updateAsset( - byte[] address, - byte[] description, - byte[] url, - long newLimit, - long newPublicLimit, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return updateAsset2( - byte[] address, - byte[] description, - byte[] url, - long newLimit, - long newPublicLimit, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static boolean transferAsset( - byte[] to, - byte[] assertName, - long amount, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean updateAccount( - byte[] addressBytes, - byte[] accountNameBytes, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean waitSolidityNodeSynFullNodeData( - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer wait = 0; - logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 - && wait - < ((getWitnessNum(blockingStubFull) >= 27) - ? 27 - : getWitnessNum(blockingStubFull) + 1)) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info( - "Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData().getNumber()); - solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - if (wait == 24) { - logger.info("Didn't syn,skip to next case."); - return false; - } - wait++; - } - return true; - } - - /** constructor. */ - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info("Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - while (nextNum <= currentNum + 1 && wait <= 45) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 45) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; - } - logger.info("quit normally"); - return true; - } - - /** constructor. */ - public static AccountNetMessage getAccountNet( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountNet(request); - } - - /* public static byte[] addPreFix(byte[] address) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Config config = Configuration.getByPath("testng.conf"); - byte ADD_PRE_FIX_BYTE_MAINNET = (byte) 0x41; //41 + address - byte ADD_PRE_FIX_BYTE_TESTNET = (byte) 0xa0; //a0 + address - byte[] preFix = new byte[1]; - if (config.hasPath("net.type") && "mainnet".equalsIgnoreCase(config.getString("net.type"))) { - WalletClient.setAddressPreFixByte(ADD_PRE_FIX_BYTE_MAINNET); - preFix[0] = ADD_PRE_FIX_BYTE_MAINNET; - }else { - WalletClient.setAddressPreFixByte(ADD_PRE_FIX_BYTE_TESTNET); - preFix[0] = ADD_PRE_FIX_BYTE_TESTNET; - } - byte[] finalAddress = new byte[preFix.length+address.length]; - System.arraycopy(preFix, 0, finalAddress, 0, preFix.length); - System.arraycopy(address, 0, finalAddress, preFix.length, address.length); - return finalAddress; - - }*/ - - /** constructor. */ - public static byte[] getFinalAddress(String priKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - WalletClient walletClient; - walletClient = new WalletClient(priKey); - // walletClient.init(0); - return walletClient.getAddress(); - } - - /** constructor. */ - public static String createAccountGetTxid( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static boolean createAccount( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return createAccount2( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static boolean voteWitness( - byte[] ownerAddress, - String priKey, - HashMap witnessMap, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - for (byte[] address : witnessMap.keySet()) { - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(witnessMap.get(address)); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static boolean createProposal( - byte[] ownerAddress, - String priKey, - HashMap parametersMap, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static boolean approveProposal( - byte[] ownerAddress, - String priKey, - long id, - boolean isAddApproval, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean deleteProposal( - byte[] ownerAddress, String priKey, long id, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean printAddress(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info(key); - logger.info(ByteArray.toHexString(getFinalAddress(key))); - logger.info(Base58.encode58Check(getFinalAddress(key))); - return true; - } - - /** constructor. */ - public static String getAddressString(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - return Base58.encode58Check(getFinalAddress(key)); - } - - /** constructor. */ - public static ArrayList getAddressInfo(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ArrayList accountList = new ArrayList(); - accountList.add(key); - accountList.add(ByteArray.toHexString(getFinalAddress(key))); - accountList.add(Base58.encode58Check(getFinalAddress(key))); - return accountList; - } - - /** constructor. */ - public static boolean setAccountId( - byte[] accountIdBytes, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Boolean freezeBalanceGetTronPower( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - ByteString receiverAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return freezeBalanceForReceiver( - addRess, - freezeBalance, - freezeDuration, - resourceCode, - receiverAddress, - priKey, - blockingStubFull); - } - - /** constructor. */ - public static Boolean freezeBalanceGetEnergy( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration) - .setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static AccountResourceMessage getAccountResource( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountResource(request); - } - - /** constructor. */ - public static boolean buyStorage( - long quantity, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setQuant(quantity); - BuyStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean sellStorage( - long quantity, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SellStorageContract.Builder builder = SellStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); - SellStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static byte[] deployContractFallbackReceive( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi2(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static byte[] deployContract( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static byte[] deployContract( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContract( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static byte[] deployContractFallback( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractFallbackReceive( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static byte[] deployContractForLibrary( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - String compilerVersion, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); - } else { - // old version - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); - } - - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static String deployContractAndGetTransactionInfoById( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static String deployContractAndGetTransactionInfoById( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null - && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null - && abiItem.getAsJsonObject().get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null - ? abiItem.getAsJsonObject().get("name").getAsString() - : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null - ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() - : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null - ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() - : null; - String type = - abiItem.getAsJsonObject().get("type") != null - ? abiItem.getAsJsonObject().get("type").getAsString() - : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null - && abiItem.getAsJsonObject().get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null - ? abiItem.getAsJsonObject().get("stateMutability").getAsString() - : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = - SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** constructor. */ - public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null - && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null - && abiItem.getAsJsonObject().get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null - ? abiItem.getAsJsonObject().get("name").getAsString() - : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null - ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() - : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null - ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() - : null; - String type = - abiItem.getAsJsonObject().get("type") != null - ? abiItem.getAsJsonObject().get("type").getAsString() - : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null - && abiItem.getAsJsonObject().get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null - ? abiItem.getAsJsonObject().get("stateMutability").getAsString() - : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") - && !type.equalsIgnoreCase("receive") - && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = - SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - entryBuilder.setType(getEntryType2(type)); - - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** constructor. */ - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "error": - return SmartContract.ABI.Entry.EntryType.Error; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "receive": - return SmartContract.ABI.Entry.EntryType.Receive; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { - - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; - - // get tx hash - byte[] txRawDataHash = - Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); - - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - - return sha3omit12(combined); - } - - /** constructor. */ - public static SmartContract getContract( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); - } - - /** constructor. */ - public static SmartContractDataWrapper getContractInfo( - byte[] address, WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info( - "contract name is " - + blockingStubFull.getContractInfo(bytesMessage).getSmartContract().getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContractInfo(bytesMessage); - } - - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = - ByteArray.toHexString(Commons.decodeFromBase58Check(addr)).substring(2); - - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - - - private static byte[] replaceLibraryAddresscompilerVersion( - String code, String libraryAddressPair, String compilerVersion) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex; - libraryAddressHex = - (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), StandardCharsets.US_ASCII)) - .substring(2); - - String beReplaced; - if (compilerVersion == null) { - // old version - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - beReplaced = "__" + libraryName + repeated; - } else if (compilerVersion.equalsIgnoreCase("v5")) { - // 0.5.4 version - String libraryNameKeccak256 = - ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))).substring(0, 34); - beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; - } else { - throw new RuntimeException("unknown compiler version."); - } - - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - /** constructor. */ - public static boolean updateSetting( - byte[] contractAddress, - long consumeUserResourcePercent, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** 61 constructor. */ - public static Optional getTransactionInfoById( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - /** 61 constructor. */ - public static Optional getTransactionInfoByIdFromSolidity( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - /** constructor. */ - public static Optional getTransactionInfoByBlockNum( - long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** constructor. */ - public static Optional getTransactionInfoByBlockNumFromSolidity( - long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** constructor. */ - public static String triggerContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return triggerContract( - contractAddress, - method, - argsStr, - isHex, - callValue, - feeLimit, - "0", - 0, - ownerAddress, - priKey, - blockingStubFull); - } - - /** constructor. */ - public static String triggerContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = new byte[0]; - if (!method.equalsIgnoreCase("#")) { - input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - } - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static String triggerContractBoth( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - return triggerContractBoth( - contractAddress, - method, - argsStr, - isHex, - callValue, - feeLimit, - "0", - 0, - ownerAddress, - priKey, - blockingStubFull, - blockingStubFull1); - } - - /** constructor. */ - public static String triggerContractBoth( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = - broadcastTransactionBoth(transaction, blockingStubFull, blockingStubFull1); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static String triggerParamListContract( - byte[] contractAddress, - String method, - List params, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Boolean exchangeCreate( - byte[] firstTokenId, - long firstTokenBalance, - byte[] secondTokenId, - long secondTokenBalance, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)) - .setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Boolean injectExchange( - long exchangeId, - byte[] tokenId, - long quant, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** constructor. */ - public static Optional getExchangeList( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ExchangeList exchangeList = - blockingStubSolidity.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** constructor. */ - public static Optional getExchange( - String id, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - BytesMessage request = - BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) - .build(); - Exchange exchange = blockingStubSolidity.getExchangeById(request); - return Optional.ofNullable(exchange); - } - - /** constructor. */ - public static Optional getExchange( - String id, WalletGrpc.WalletBlockingStub blockingStubFull) { - BytesMessage request = - BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) - .build(); - Exchange exchange = blockingStubFull.getExchangeById(request); - return Optional.ofNullable(exchange); - } - - /** constructor. */ - public static boolean exchangeWithdraw( - long exchangeId, - byte[] tokenId, - long quant, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean exchangeTransaction( - long exchangeId, - byte[] tokenId, - long quant, - long expected, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant) - .setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static String deployContractWithConstantParame( - String contractName, - String abiString, - String code, - String constructorStr, - String argsStr, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame( - contractName, - abiString, - code, - constructorStr, - argsStr, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static String deployContractWithConstantParame( - String contractName, - String abiString, - String code, - String constructorStr, - String argsStr, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Boolean freezeBalanceForReceiver( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - ByteString receiverAddressBytes, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration) - .setResourceValue(resourceCode); - if (receiverAddressBytes != null) { - builder.setReceiverAddress(receiverAddressBytes); - } - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Optional getDelegatedResource( - byte[] fromAddress, byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = - DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs) - .setToAddress(toAddressBs) - .build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } - - /** constructor. */ - public static Optional getDelegatedResourceFromSolidity( - byte[] fromAddress, - byte[] toAddress, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = - DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs) - .setToAddress(toAddressBs) - .build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } - - /** constructor. */ - public static Optional getDelegatedResourceAccountIndex( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ByteString addressBs = ByteString.copyFrom(address); - - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - - DelegatedResourceAccountIndex accountIndex = - blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } - - /** constructor. */ - public static Optional - getDelegatedResourceAccountIndexFromSolidity( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ByteString addressBs = ByteString.copyFrom(address); - - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - - DelegatedResourceAccountIndex accountIndex = - blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByName( - String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByNameFromSolidity( - String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } - - /** constructor. */ - public static Optional getAssetIssueListByName( - String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional getAssetIssueListByNameFromSolidity( - String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listAssetIssueFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.AssetIssueList assetIssueList = - blockingStubFull.getAssetIssueList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listAssetIssuepaginatedFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { - GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = - blockingStubFull.getPaginatedAssetIssueList(pageMessageBuilder.build()); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listWitnesses( - WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - /** constructor. */ - public static Optional listWitnessesFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueById( - String assetId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByIdFromSolidity( - String assetId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** constructor. */ - public static Optional getAssetIssueByAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); - return Optional.ofNullable(assetIssueList); - } - - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - // long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - long weight = Long.parseLong(key.getString("weight")); - // long weight = key.getLong("weight"); - // keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } - - /** constructor. */ - public static boolean accountPermissionUpdate( - String permissionJson, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static long getFreezeBalanceCount( - byte[] accountAddress, - String ecKey, - Long targetEnergy, - WalletGrpc.WalletBlockingStub blockingStubFull) { - // Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - - Account info = queryAccount(accountAddress, blockingStubFull); - - Account getAccount = queryAccount(ecKey, blockingStubFull); - - long balance = info.getBalance(); - long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); - long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); - long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); - long energyUsed = resourceInfo.getEnergyUsed(); - long energyLimit = resourceInfo.getEnergyLimit(); - - if (energyUsed > energyLimit) { - targetEnergy = energyUsed - energyLimit + targetEnergy; - } - - if (totalEnergyWeight == 0) { - return 1000_000L; - } - - // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance - final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); - long needBalance = - totalEnergyWeightBi - .multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetEnergy)) - .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)) - .longValue(); - - logger.info("getFreezeBalanceCount, needBalance: " + needBalance); - - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** constructor. */ - public static Long getAssetIssueValue( - byte[] accountAddress, - ByteString assetIssueId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Long assetIssueCount = 0L; - Account contractAccount = queryAccount(accountAddress, blockingStubFull); - Map createAssetIssueMap = contractAccount.getAssetV2Map(); - for (Map.Entry entry : createAssetIssueMap.entrySet()) { - if (assetIssueId.toStringUtf8().equals(entry.getKey())) { - assetIssueCount = entry.getValue(); - } - } - return assetIssueCount; - } - - /** constructor. */ - public static List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; - } - - /** constructor. */ - public static String byte2HexStr(byte[] b, int offset, int length) { - StringBuilder ssBuilder = new StringBuilder(); - for (int n = offset; n < offset + length && n < b.length; n++) { - String stmp = Integer.toHexString(b[n] & 0xFF); - ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); - } - return ssBuilder.toString().toUpperCase().trim(); - } - - /** constructor. */ - public static Transaction addTransactionSign( - Transaction transaction, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** constructor. */ - public static GrpcAPI.Return deployContractAndGetResponse( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response; - } - - /** constructor. */ - public static GrpcAPI.Return triggerContractAndGetResponse( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response; - } - - /** constructor. */ - public static boolean updateEnergyLimit( - byte[] contractAddress, - long originEnergyLimit, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static GrpcAPI.Return accountPermissionUpdateForResponse( - String permissionJson, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response; - } - - public static TransactionApprovedList getTransactionApprovedList( - Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionApprovedList(transaction); - } - - /** constructor. */ - public static long getFreezeBalanceNetCount( - byte[] accountAddress, - String ecKey, - Long targetNet, - WalletGrpc.WalletBlockingStub blockingStubFull) { - // Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - - Account info = queryAccount(accountAddress, blockingStubFull); - - Account getAccount = queryAccount(ecKey, blockingStubFull); - - long balance = info.getBalance(); - long totalNetLimit = resourceInfo.getTotalNetLimit(); - long totalNetWeight = resourceInfo.getTotalNetWeight(); - long netUsed = resourceInfo.getNetUsed(); - long netLimit = resourceInfo.getNetLimit(); - - if (netUsed > netLimit) { - targetNet = netUsed - netLimit + targetNet; - } - - if (totalNetWeight == 0) { - return 1000_000L; - } - - // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance - final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); - long needBalance = - totalNetWeightBi - .multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetNet)) - .divide(BigInteger.valueOf(totalNetLimit - targetNet)) - .longValue(); - - logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); - - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info( - "getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** constructor. */ - public static GrpcAPI.Return broadcastTransaction( - Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { - int i = 10; - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } - - /** constructor. */ - public static GrpcAPI.Return broadcastTransactionBoth( - Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - int i = 10; - waitProduceNextBlock(blockingStubFull1); - GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); - GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); - while (response.getResult() == false - && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } - - /** constructor. */ - public static String exec(String command) throws InterruptedException { - String returnString = ""; - Process pro = null; - Runtime runTime = Runtime.getRuntime(); - if (runTime == null) { - logger.error("Create runtime false!"); - } - try { - pro = runTime.exec(command); - BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); - PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); - String line; - while ((line = input.readLine()) != null) { - returnString = returnString + line + "\n"; - } - input.close(); - output.close(); - pro.destroy(); - } catch (IOException ex) { - logger.error(null, ex); - } - return returnString; - } - - /** constructor. */ - public static HashMap getBycodeAbiNoOptimize( - String solFile, String contractName) { - final String compile = - Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile - + " --bin --abi --overwrite " - + absolutePath - + "/" - + solFile - + " -o " - + absolutePath - + "/" - + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } - - /** constructor. */ - public static HashMap getBycodeAbi(String solFile, String contractName) { - final String compile = - Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile - + " --optimize --bin --abi --overwrite " - + absolutePath - + "/" - + solFile - + " -o " - + absolutePath - + "/" - + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } - - /** constructor. */ - public static String fileRead(String filePath, boolean isLibrary) throws Exception { - File file = new File(filePath); - FileReader reader = new FileReader(file); - BufferedReader breader = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - if (!isLibrary) { - if ((s = breader.readLine()) != null) { - sb.append(s); - } - breader.close(); - } else { - String fistLine = breader.readLine(); - breader.readLine(); - if ((s = breader.readLine()) != null && !s.equals("")) { - s = s.substring(s.indexOf("-> ") + 3); - sb.append(s + ":"); - } else { - s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); - sb.append(s + ":"); - } - breader.close(); - } - return sb.toString(); - } - - /** constructor. */ - public static HashMap getBycodeAbiForLibrary( - String solFile, String contractName) { - HashMap retMap = null; - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode/output" + dirPath; - try { - retMap = PublicMethed.getBycodeAbi(solFile, contractName); - String library = fileRead(outputPath + "/" + contractName + ".bin", true); - retMap.put("library", library); - logger.debug("library: " + library); - } catch (Exception e) { - e.printStackTrace(); - } - - return retMap; - } - - /** constructor. */ - public static String triggerConstantContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - blockingStubFull.triggerConstantContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static TransactionExtention triggerConstantContractForExtentionOnSolidity( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - blockingStubSolidity.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static String clearContractAbi( - byte[] contractAddress, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearAbiContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static TransactionExtention clearContractAbiForExtention( - byte[] contractAddress, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearAbiContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerConstantContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { - logger.info("tokenid is 0"); - tokenId = "0"; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerSolidityContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - solidityBlockingStubFull.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static String create2(String[] parameters) { - if (parameters == null || parameters.length != 3) { - logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); - return null; - } - - byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); - if (!WalletClient.addressValid(address)) { - logger.error("length of address must be 21 bytes."); - return null; - } - - byte[] code = Hex.decode(parameters[1]); - byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); - if (temp.length != 8) { - logger.error("Invalid salt!"); - return null; - } - byte[] salt = new byte[32]; - System.arraycopy(temp, 0, salt, 24, 8); - - byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); - String create2Address = Base58.encode58Check(sha3omit12(mergedData)); - - logger.info("create2 Address: " + create2Address); - - return create2Address; - } - - /** constructor. */ - public static boolean sendShieldCoin( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = - any.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - return broadcastTransaction(transaction, blockingStubFull).getResult(); - } - - /** constructor. */ - public static boolean sendShieldCoinWithoutAsk( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - byte[] ask = new byte[32]; - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() != 1) { - System.out.println("Can't get all merkel tree, please check the notes."); - return false; - } - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); - builder.setAk( - ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransactionWithoutSpendAuthSig(builder.build()); - if (transactionExtention == null) { - System.out.println("sendShieldCoinWithoutAsk failure."); - return false; - } - BytesMessage trxHash = - blockingStubFull.getShieldTransactionHash(transactionExtention.getTransaction()); - if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { - System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - System.out.println("This method only for ShieldedTransferContract, please check!"); - return false; - } - Any any = transaction.getRawData().getContract(0).getParameter(); - Transaction transaction1 = transactionExtention.getTransaction(); - try { - ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); - List spendDescList = shieldContract.getSpendDescriptionList(); - ShieldedTransferContract.Builder contractBuild = - shieldContract.toBuilder().clearSpendDescription(); - for (int i = 0; i < spendDescList.size(); i++) { - - SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); - builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); - SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - spendDescription.setSpendAuthoritySignature( - ByteString.copyFrom(authSig.getValue().toByteArray())); - - contractBuild.addSpendDescription(spendDescription.build()); - } - - Transaction.raw.Builder rawBuilder = - transaction.toBuilder() - .getRawDataBuilder() - .clearContract() - .addContract( - Transaction.Contract.newBuilder() - .setType(ContractType.ShieldedTransferContract) - .setParameter(Any.pack(contractBuild.build())) - .build()); - - transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); - - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction1 = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - if (transaction1.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - transaction1 = signTransaction(ecKey, transaction1); - } else { - Any any1 = transaction1.getRawData().getContract(0).getParameter(); - ShieldedTransferContract shieldedTransferContract = - any1.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction1 = signTransactionForShield(ecKey, transaction1); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - } - } - } catch (Exception e) { - System.out.println(e); - } - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - return broadcastTransaction(transaction1, blockingStubFull).getResult(); - } - - /** constructor. */ - public static List addShieldOutputList( - List shieldOutList, String shieldToAddress, String toAmountString, String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - try { - noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - // logger.info(shieldOutList.toString()); - return shieldOutList; - } - - /** constructor. */ - public static Optional generateShieldAddress() { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - try { - DiversifierT diversifier = DiversifierT.random(); - SpendingKey spendingKey = SpendingKey.random(); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); - - addressInfo.setSk(spendingKey.getValue()); - addressInfo.setD(diversifier); - addressInfo.setIvk(incomingViewingKey.getValue()); - addressInfo.setOvk(fullViewingKey.getOvk()); - addressInfo.setPkD(paymentAddress.getPkD()); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** constructor. */ - public static DecryptNotes listShieldNote( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } - } - - /** constructor. */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByOvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByOvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static String getMemo(Note note) { - return ZenUtils.getMemo(note.getMemo().toByteArray()); - } - - /** constructor. */ - public static SpendResult getSpendResult( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = - Optional.of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); - logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - return result; - } - return null; - } - - /** constructor. */ - public static SpendResult getSpendResultOnSolidity( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = - Optional.of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubSolidity.isSpend(builder.build()); - return result; - } - return null; - } - - /** constructor. */ - public static String getShieldNullifier( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() < 1) { - System.out.println("get merkleVoucherInfo failure."); - return null; - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - // TODO - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - NfParameters.Builder builder = NfParameters.newBuilder(); - builder.setNote(noteBuild.build()); - builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); - builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); - - BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); - return ByteArray.toHexString(nullifier.getValue().toByteArray()); - - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** constructor. */ - public static String sendShieldCoinGetTxid( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = - any.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - /** constructor. */ - public static byte[] decode58Check(String input) { - byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); - if (decodeCheck.length <= 4) { - return null; - } - byte[] decodeData = new byte[decodeCheck.length - 4]; - System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); - if (hash1[0] == decodeCheck[decodeData.length] - && hash1[1] == decodeCheck[decodeData.length + 1] - && hash1[2] == decodeCheck[decodeData.length + 2] - && hash1[3] == decodeCheck[decodeData.length + 3]) { - return decodeData; - } - return null; - } - - /** constructor. */ - public static void freedResource( - byte[] fromAddress, - String priKey, - byte[] toAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); - sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); - } - - /** constructor. */ - public static String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } - - /** constructor. */ - public static String bytes32ToString(byte[] bytes) { - if (bytes == null) { - return "null"; - } - int imax = bytes.length - 1; - if (imax == -1) { - return ""; - } - - StringBuilder b = new StringBuilder(); - for (int i = 0; ; i++) { - b.append(bytes[i]); - if (i == imax) { - return b.toString(); - } - } - } - - /** constructor. */ - public static Return transferAssetForReturn( - byte[] to, - byte[] assertName, - long amount, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.transferAsset2(contract); - - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; - } - - /** constructor. */ - public static Return sendcoinForReturn( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.createTransaction2(contract); - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; - } - - /** constructor. */ - public static Transaction sendcoinForTransaction( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention extention = blockingStubFull.createTransaction2(contract); - Protocol.Transaction transaction = extention.getTransaction(); - return transaction; - } - - /** constructor. */ - public static String marketSellAsset( - byte[] owner, - String priKey, - byte[] sellTokenId, - long sellTokenQuantity, - byte[] buyTokenId, - long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = - MarketContract.MarketSellAssetContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } - - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); - - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - - System.out.println("trigger txid = " + txid); - return txid; - } - - /** constructor. */ - public static Return marketSellAssetGetResposne( - byte[] owner, - String priKey, - byte[] sellTokenId, - long sellTokenQuantity, - byte[] buyTokenId, - long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = - MarketContract.MarketSellAssetContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - - return transactionExtention.getResult(); - } - - /** constructor. */ - public static String marketCancelOrder( - byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketCancelOrderContract.Builder builder = - MarketContract.MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret.getMessage().toStringUtf8(); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } - - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); - - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - - System.out.println("trigger txid = " + txid); - - return txid; - } - - /** constructor. */ - public static Return marketCancelOrderGetResposne( - byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - MarketContract.MarketCancelOrderContract.Builder builder = - MarketContract.MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return null; - } - return transactionExtention.getResult(); - } - - /** constructor. */ - public static Optional getMarketOrderByAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubFull.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderByAccountSolidity( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderById( - byte[] order, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** constructor. */ - public static Optional getMarketOrderByIdSolidity( - byte[] order, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** constructor. */ - public static Optional getMarketPriceByPair( - byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); - return Optional.ofNullable(marketPriceList); - } - - /** constructor. */ - public static Optional getMarketOrderListByPair( - byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderListByPairSolidity( - byte[] sellTokenId, - byte[] buyTokenId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = - blockingStubSolidity.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketPairList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPairList marketOrderList = - blockingStubFull.getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketPairListSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPairList marketOrderList = - blockingStubSolidity.getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static String stringToHexString(String s) { - String str = ""; - for (int i = 0; i < s.length(); i++) { - int ch = s.charAt(i); - String s4 = Integer.toHexString(ch); - str = str + s4; - } - return str; - } - - /** constructor. */ - public static String hexStringToString(String s) { - if (s == null || s.equals("")) { - return null; - } - s = s.replace(" ", ""); - byte[] baKeyword = new byte[s.length() / 2]; - for (int i = 0; i < baKeyword.length; i++) { - try { - baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - s = new String(baKeyword, "gbk"); - new String(); - } catch (Exception e1) { - e1.printStackTrace(); - } - return s; - } - - /** constructor. */ - public static String removeAll0sAtTheEndOfHexStr(String s) { - return s.replaceAll("(00)+$", ""); - } - - /** constructor. */ - public static String replaceCode(String code, String address) { - if (code.indexOf("__$") == -1) { - return code; - } else { - int index = code.indexOf("_"); - String oldStr = code.substring(index - 1, index + 39); - Pattern p = Pattern.compile(oldStr); - Matcher m = p.matcher(code); - String result = m.replaceAll(address); - return result; - } - } - - /** constructor. */ - public static Map getAllowance2( - Long startNum, Long endNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - final String blackHole = - Configuration.getByPath("testng.conf").getString("defaultParameter.blackHoleAddress"); - Long totalCount = 0L; - Map witnessBlockCount = new HashMap<>(); - Map witnessBrokerage = new HashMap<>(); - Map witnessVoteCount = new HashMap<>(); - Map witnessAllowance = new HashMap<>(); - List witnessList = - PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList(); - for (Protocol.Witness witness : witnessList) { - witnessVoteCount.put( - ByteArray.toHexString(witness.getAddress().toByteArray()), witness.getVoteCount()); - GrpcAPI.BytesMessage bytesMessage = - GrpcAPI.BytesMessage.newBuilder().setValue(witness.getAddress()).build(); - Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); - witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); - totalCount += witness.getVoteCount(); - } - Optional infoById = null; - for (Long k = startNum; k < endNum; k++) { - String witnessAdd = - ByteArray.toHexString( - PublicMethed.getBlock(k, blockingStubFull) - .getBlockHeader() - .getRawData() - .getWitnessAddress() - .toByteArray()); - witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); - List transList = - PublicMethed.getBlock(k, blockingStubFull).getTransactionsList(); - for (Transaction tem : transList) { - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); - logger.info("----ss txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long packingFee = infoById.get().getPackingFee(); - - witnessAllowance.put( - witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) + packingFee); - } - } - - logger.info("========totalCount:" + totalCount); - List chainParaList = - blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()) - .getChainParameterList(); - Long witness127PayPerBlock = 0L; - Long witnessPayPerBlock = 0L; - for (Protocol.ChainParameters.ChainParameter para : chainParaList) { - if ("getWitness127PayPerBlock".equals(para.getKey())) { - witness127PayPerBlock = para.getValue(); - } - if ("getWitnessPayPerBlock".equals(para.getKey())) { - witnessPayPerBlock = para.getValue(); - } - } - logger.info( - "witness127PayPerBlock:" - + witness127PayPerBlock - + "\n witnessPayPerBlock:" - + witnessPayPerBlock); - - for (Map.Entry entry : witnessBrokerage.entrySet()) { - logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessVoteCount.entrySet()) { - logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessBlockCount.entrySet()) { - logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); - } - - for (Map.Entry entry : witnessVoteCount.entrySet()) { - String witnessAdd = entry.getKey(); - logger.info( - "----witnessAdd:" - + witnessAdd - + " block count:" - + witnessBlockCount.get(witnessAdd) - + " all: " - + witnessAllowance.getOrDefault(witnessAdd, 0L)); - Long pay = - (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) - / 100; - - witnessAllowance.put(witnessAdd, pay); - logger.info("****** " + witnessAdd + " : " + pay); - } - return witnessAllowance; - } - - public static String getContractStringMsg(byte[] contractMsgArray) { - int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); - return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); - } - - /** constructor. */ - public boolean updateBrokerage( - byte[] owner, int brokerage, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = - blockingStubFull.updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Long getAccountBalance( - Protocol.Block block, byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = - new BlockId( - org.tron.common.utils.Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - - BalanceContract.AccountIdentifier accountIdentifier = - BalanceContract.AccountIdentifier.newBuilder() - .setAddress(ByteString.copyFrom(address)) - .build(); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = - BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()) - .setNumber(blockNum) - .build(); - - BalanceContract.AccountBalanceRequest accountBalanceRequest = - BalanceContract.AccountBalanceRequest.newBuilder() - .setAccountIdentifier(accountIdentifier) - .setBlockIdentifier(blockIdentifier) - .build(); - return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); - } - - /** constructor. */ - public static BalanceContract.BlockBalanceTrace getBlockBalance( - Protocol.Block block, WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = - new BlockId( - org.tron.common.utils.Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = - BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()) - .setNumber(blockNum) - .build(); - - return blockingStubFull.getBlockBalanceTrace(blockIdentifier); - } - - /** 61 constructor. */ - public static Optional getTransactionFromPending( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction; - transaction = blockingStubFull.getTransactionFromPending(request); - return Optional.ofNullable(transaction); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java deleted file mode 100644 index 87256d07453..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java +++ /dev/null @@ -1,5335 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import static org.tron.common.crypto.Hash.sha3omit12; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PrivateParameters; -import org.tron.api.GrpcAPI.ReceiveNote; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.SpendNote; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletGrpc.WalletBlockingStub; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.CancelException; -import org.tron.core.zen.address.ExpandedSpendingKey; -import org.tron.core.zen.address.SpendingKey; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Key; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.Transaction.Result; -import org.tron.protos.Protocol.Transaction.raw; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AccountContract.SetAccountIdContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; -import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; -import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract; -import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract; -import org.tron.protos.contract.MarketContract; -import org.tron.protos.contract.ProposalContract.ProposalApproveContract; -import org.tron.protos.contract.ProposalContract.ProposalCreateContract; -import org.tron.protos.contract.ProposalContract.ProposalDeleteContract; -import org.tron.protos.contract.ShieldContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract.Builder; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; - - -public class PublicMethedForMutiSign { - - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - Wallet wallet = new Wallet(); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - - /** - * constructor. - */ - - public static Boolean createAssetIssueWithpermissionId(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - Return ret = transactionExtention.getResult(); - if (transactionExtention == null) { - return false; - } - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static String createAssetIssueForTransactionId(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static boolean broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - Return response = PublicMethed.broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** - * constructor. - */ - public static Account queryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - - /** - * constructor. - */ - - public static Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - /** - * constructor. - */ - - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public static Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public static Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - /** - * constructor. - */ - - public static Transaction signTransaction(ECKey ecKey, Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - private static Transaction signTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - if (transaction.getRawData().getTimestamp() == 0) { - transaction = TransactionUtils.setTimestamp(transaction); - } - - long currentTime = System.currentTimeMillis();//*1000000 + System.nanoTime()%1000000; - Transaction.Builder builder = transaction.toBuilder(); - org.tron.protos.Protocol.Transaction.raw.Builder rowBuilder = transaction.getRawData() - .toBuilder(); - rowBuilder.setTimestamp(currentTime); - builder.setRawData(rowBuilder.build()); - transaction = builder.build(); - - for (int i = 0; i < priKeys.length; i += 1) { - String priKey = priKeys[i]; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - transaction = TransactionUtils.sign(transaction, ecKey); - TransactionSignWeight weight = blockingStubFull.getTransactionSignWeight(transaction); - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION) { - break; - } - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION) { - continue; - } - } - return transaction; - } - - - /** - * constructor. - */ - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean participateAssetIssueWithPermissionId(byte[] to, byte[] assertName, - long amount, byte[] from, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String participateAssetIssueForTransactionId(byte[] to, byte[] assertName, - long amount, byte[] from, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return null; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int permissionId, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static Boolean unFreezeBalanceWithPermissionId(byte[] address, String priKey, - int resourceCode, byte[] receiverAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray - .toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - - } - - - /** - * constructor. - */ - public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean updateAssetWithPermissionId(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String updateAssetForTransactionId(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean transferAssetWithpermissionId(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String transferAssetForTransactionId(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info( - "Block num is " + Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - while (nextNum <= currentNum + 1 && wait <= 15) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 15) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; - } - logger.info("quit normally"); - return true; - } - - /** - * constructor. - */ - - public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean createAccountWhtiPermissionId(byte[] ownerAddress, byte[] newAddress, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean createProposalWithPermissionId(byte[] ownerAddress, String priKey, - HashMap parametersMap, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean approveProposalWithPermission(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean deleteProposalWithPermissionId(byte[] ownerAddress, String priKey, long id, - int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - return deployContract(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull, permissionKeyString); - } - - /** - * constructor. - */ - - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = PublicMethed - .generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - broadcastTransaction(transaction, blockingStubFull); - return contractAddress; - } - - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, - value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - byte[] contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null ? abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean() : false; - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null ? abiItem.getAsJsonObject() - .get("constant").getAsBoolean() : false; - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null ? abiItem.getAsJsonObject() - .get("payable").getAsBoolean() : false; - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - paramBuilder.setIndexed(false); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - paramBuilder.setIndexed(false); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; - } - } - - /** - * constructor. - */ - - public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - Integer i = 0; - while (blockingStubFull.getContract(bytesMessage).getName().isEmpty() && i++ < 4) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); - } - - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) - .substring(2); - - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { - - String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); - - Matcher m = Pattern.compile("__.*__").matcher(code); - code = m.replaceAll(libraryAddressHex); - return Hex.decode(code); - } - - /** - * constructor. - */ - - public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateSettingWithPermissionId(byte[] contractAddress, - long consumeUserResourcePercent, String priKey, byte[] ownerAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateEnergyLimitWithPermissionId(byte[] contractAddress, - long originEnergyLimit, String priKey, byte[] ownerAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull, permissionKeyString); - } - - /** - * constructor. - */ - - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** - * constructor. - */ - - public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, - data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, - ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - byte[] contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - builder.setReceiverAddress(receiverAddressBytes); - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - // long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - // long weight = key.getLong("weight"); - long weight = Long.parseLong(key.getString("weight")); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } - - /** - * constructor. - */ - - public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static String accountPermissionUpdateForTransactionId(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - - /** - * constructor. - */ - public static String accountPermissionUpdateForTransactionId1(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** - * constructor. - */ - public static Boolean voteWitness(HashMap witness, byte[] addRess, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static void printPermissionList(List permissionList) { - String result = "\n"; - result += "["; - result += "\n"; - int i = 0; - for (Permission permission : permissionList) { - result += "permission " + i + " :::"; - result += "\n"; - result += "{"; - result += "\n"; - result += printPermission(permission); - result += "\n"; - result += "}"; - result += "\n"; - i++; - } - result += "]"; - System.out.println(result); - } - - /** - * constructor. - */ - public static String printPermission(Permission permission) { - StringBuffer result = new StringBuffer(); - result.append("permission_type: "); - result.append(permission.getType()); - result.append("\n"); - result.append("permission_id: "); - result.append(permission.getId()); - result.append("\n"); - result.append("permission_name: "); - result.append(permission.getPermissionName()); - result.append("\n"); - result.append("threshold: "); - result.append(permission.getThreshold()); - result.append("\n"); - result.append("parent_id: "); - result.append(permission.getParentId()); - result.append("\n"); - result.append("operations: "); - result.append(ByteArray.toHexString(permission.getOperations().toByteArray())); - result.append("\n"); - if (permission.getKeysCount() > 0) { - result.append("keys:"); - result.append("\n"); - result.append("["); - result.append("\n"); - for (Key key : permission.getKeysList()) { - result.append(printKey(key)); - } - result.append("]"); - result.append("\n"); - } - return result.toString(); - } - - /** - * constructor. - */ - public static String printKey(Key key) { - StringBuffer result = new StringBuffer(); - result.append("address: "); - result.append(encode58Check(key.getAddress().toByteArray())); - result.append("\n"); - result.append("weight: "); - result.append(key.getWeight()); - result.append("\n"); - return result.toString(); - } - - /** - * constructor. - */ - public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), hash0); - byte[] inputCheck = new byte[input.length + 4]; - System.arraycopy(input, 0, inputCheck, 0, input.length); - System.arraycopy(hash1, 0, inputCheck, input.length, 4); - return Base58.encode(inputCheck); - } - - /** - * constructor. - */ - public static Transaction sendcoinWithPermissionIdNotSign(byte[] to, long amount, byte[] owner, - int permissionId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - - return transaction; - - } - - /** - * constructor. - */ - public static TransactionSignWeight getTransactionSignWeight(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionSignWeight(transaction); - } - - /** - * constructor. - */ - public static Return broadcastTransaction1(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - return PublicMethed.broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean accountPermissionUpdateWithPermissionId(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static Transaction accountPermissionUpdateWithoutSign(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transaction; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - return transaction; - } - - /** - * constructor. - */ - public static Transaction addTransactionSignWithPermissionId(Transaction transaction, - String priKey, int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - - //transaction = setPermissionId(transaction, permissionId); - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permissionId); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); - ECKey ecKey = temKey; - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** - * constructor. - */ - public static Transaction setPermissionId(Transaction transaction, int permissionId) - throws CancelException { - if (transaction.getSignatureCount() != 0 - || transaction.getRawData().getContract(0).getPermissionId() != 0) { - return transaction; - } - if (permissionId < 0) { - throw new CancelException("User cancelled"); - } - if (permissionId != 0) { - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permissionId); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - } - return transaction; - } - - /** - * constructor. - */ - public static int getActivePermissionKeyCount(List permissionList) { - int permissionCount = 0; - for (Permission permission : permissionList) { - permissionCount += permission.getKeysCount(); - } - return permissionCount; - } - - /** - * constructor. - */ - public static Boolean sendcoinWithPermissionId(byte[] to, long amount, byte[] owner, - int permissionId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - public static void recoverWitnessPermission(String ownerKey, List ownerPermissionKeys, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - PublicMethed.printAddress(ownerKey); - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue( - accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - } - - /** - * constructor. - */ - public static String getOperations(Integer[] ints) { - List list = new ArrayList<>(Arrays.asList(ints)); - byte[] operations = new byte[32]; - list.forEach(e -> { - operations[e / 8] |= (1 << e % 8); - }); - - System.out.println(ByteArray.toHexString(operations)); - return ByteArray.toHexString(operations); - } - - /** - * constructor. - */ - public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response; - } - - /** - * constructor. - */ - public static void recoverAccountPermission(String ownerKey, List ownerPermissionKeys, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - PublicMethed.printAddress(ownerKey); - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue( - accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - } - - /** - * constructor. - */ - public static Transaction sendcoin2(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - return transaction; - - } - - /** - * constructor. - */ - public static Protocol.Transaction createFakeTransaction(byte[] toAddrss, Long amount, - byte[] fromAddress) { - - TransferContract contract = TransferContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(fromAddress)) - .setToAddress(ByteString.copyFrom(toAddrss)).setAmount(amount).build(); - Protocol.Transaction transaction = createTransaction(contract, ContractType.TransferContract); - - return transaction; - } - - /** - * constructor. - */ - private static Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)).build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - /** - * constructor. - */ - public static Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - /** - * constructor. - */ - public static Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter(Any.pack(message)) - .build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long geTime = count.incrementAndGet() + time; - String ref = "" + geTime; - - transaction = setReference(transaction, geTime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, geTime); - - return transaction; - } - - /** - * constructor. - */ - - public static String triggerContractWithPermissionId(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString, int permissionId) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { - - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; - - // get tx hash - byte[] txRawDataHash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), trx.getRawData().toByteArray()).getBytes(); - - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - - return sha3omit12(combined); - - } - - /** - * constructor. - */ - - public static byte[] deployContractWithPermissionId(String contractName, String abiString, - String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString, int permissionId) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } - } - - - /** - * constructor. - */ - public static byte[] deployContract1(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0L); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = PublicMethed - .generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - broadcastTransaction(transaction, blockingStubFull); - return contractAddress; - } - - /** - * constructor. - */ - public static String triggerContract1(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong("0")); - builder.setCallTokenValue(0L); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static boolean updateAccountWithPermissionId(byte[] addressBytes, byte[] accountNameBytes, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static String transferAssetForTransactionId1(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (result == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergyWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = TransactionUtils.setTimestamp(transaction); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiverWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - builder.setReceiverAddress(receiverAddressBytes); - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean createAccount1(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean setAccountId1(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return broadcastTransaction(transaction, blockingStubFull); - //Return response = broadcastTransaction1(transaction, blockingStubFull); - //if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - // return false; - //} else { - // return true; - //} - //return response.getResult(); - } - - - /** - * constructor. - */ - public static Boolean voteWitnessWithPermissionId(HashMap witness, byte[] addRess, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - Transaction transaction = transactionExtention.getTransaction(); - - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String createAssetIssueForTransactionId1(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (result == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - - public static Boolean injectExchange1(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean exchangeWithdraw1(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean exchangeTransaction1(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean exchangeCreate1(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearABIContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearABIContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return false; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, Integer permission_id, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldContract.ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldContract.ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permission_id); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - - transaction = signTransactionForShield(transaction, blockingStubFull, permissionKeyString); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - private static Transaction signTransactionForShield(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - /* if (transaction.getRawData().getTimestamp() == 0) { - transaction = TransactionUtils.setTimestamp(transaction); - } - - long currentTime = System.currentTimeMillis();//*1000000 + System.nanoTime()%1000000; - Transaction.Builder builder = transaction.toBuilder(); - org.tron.protos.Protocol.Transaction.raw.Builder rowBuilder = transaction.getRawData() - .toBuilder(); - rowBuilder.setTimestamp(currentTime); - builder.setRawData(rowBuilder.build()); - transaction = builder.build();*/ - - for (int i = 0; i < priKeys.length; i += 1) { - String priKey = priKeys[i]; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - transaction = TransactionUtils.sign(transaction, ecKey); - TransactionSignWeight weight = blockingStubFull.getTransactionSignWeight(transaction); - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION) { - break; - } - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION) { - continue; - } - } - logger.info("Sign transaction:" + transaction.toString()); - return transaction; - } - - /** - * constructor. - */ - public static boolean createWitness(String url, byte[] owner, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] byteurl = url.getBytes(); - WitnessCreateContract.Builder builder = WitnessCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(byteurl)); - WitnessCreateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateWitness2(byte[] owner, byte[] url, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessUpdateContract.Builder builder = WitnessUpdateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessUpdateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult().getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - public static boolean withdrawBalance(byte[] address, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return true; - } - - /** - * constructor. - */ - public static boolean unFreezeAsset(byte[] addRess, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address = addRess; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - UnfreezeAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return true; - } - - /** - * constructor. - */ - - public static Transaction sendcoinGetTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return transaction; - - } - - /** - * constructor. - */ - public static boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - int permissionId, String[] priKeys, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction, blockingStubFull, priKeys); - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean marketSellAsset(byte[] owner, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - int permissionId, String[] priKeys, WalletBlockingStub blockingStubFull) { - - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - if (transaction.getRawData().getContract(0).getType() - != ContractType.MarketSellAssetContract) { - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction, blockingStubFull, priKeys); - } catch (CancelException e) { - e.printStackTrace(); - } - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - public static boolean marketCancelOrder(byte[] owner, byte[] orderId, - int permissionId, String[] priKeys, - WalletBlockingStub blockingStubFull) { - - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - if (transaction.getRawData().getContract(0).getType() - != ContractType.MarketCancelOrderContract) { - System.out.println("Wrong ContractType :" - + transaction.getRawData().getContract(0).getType()); - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction,blockingStubFull,priKeys); - } catch (CancelException e) { - e.printStackTrace(); - } - return broadcastTransaction(transaction, blockingStubFull); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java deleted file mode 100644 index 8c9779504f9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java +++ /dev/null @@ -1,50 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import org.testng.IRetryAnalyzer; -import org.testng.ITestResult; - -public class Retry implements IRetryAnalyzer { - - private int retryCount = 0; - private int maxRetryCount = 2; - - // Below method returns 'true' if the test method has to be retried else 'false' - //and it takes the 'Result' as parameter of the test method that just ran - - /** - * constructor. - */ - - public boolean retry(ITestResult result) { - if (retryCount < maxRetryCount) { - System.out.println("Retrying test " + result.getName() + " with status " - + getResultStatusName(result.getStatus()) + " for the " + (retryCount + 1) + " time(s)."); - retryCount++; - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return true; - } - return false; - } - - /** - * constructor. - */ - - public String getResultStatusName(int status) { - String resultName = null; - if (status == 1) { - resultName = "SUCCESS"; - } - if (status == 2) { - resultName = "FAILURE"; - } - if (status == 3) { - resultName = "SKIP"; - } - return resultName; - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java deleted file mode 100644 index 1e2ac832377..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java +++ /dev/null @@ -1,20 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import org.testng.IAnnotationTransformer; -import org.testng.IRetryAnalyzer; -import org.testng.annotations.ITestAnnotation; - -public class RetryListener implements IAnnotationTransformer { - - @Override - public void transform(ITestAnnotation testannotation, Class testClass, - Constructor testConstructor, Method testMethod) { - IRetryAnalyzer retry = testannotation.getRetryAnalyzer(); - - if (retry == null) { - testannotation.setRetryAnalyzer(Retry.class); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java deleted file mode 100644 index 6dd758a1501..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java +++ /dev/null @@ -1,346 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -/* - * Copyright 2011 Google Inc. - * Copyright 2014 Andreas Schildbach - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.protobuf.ByteString; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.tron.common.utils.ByteArray; - - -/** - * A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be - * used as keys in a map. It also checks that the length is correct and provides a bit more type - * safety. - */ -public class Sha256Hash implements Serializable, Comparable { - - public static final int LENGTH = 32; // bytes - public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]); - - private final byte[] bytes; - - private long blockNum; - - - /** - * constructor. - */ - - public Sha256Hash(long num, byte[] hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - this.blockNum = num; - } - - /** - * constructor. - */ - - public Sha256Hash(long num, Sha256Hash hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - this.blockNum = num; - } - - /** - * Use {@link #wrap(byte[])} instead. - */ - @Deprecated - public Sha256Hash(byte[] rawHashBytes) { - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Creates a new instance that wraps the given hash value. - * - * @param rawHashBytes the raw hash bytes to wrap - * @return a new instance - * @throws IllegalArgumentException if the given array length is not exactly 32 - */ - @SuppressWarnings("deprecation") // the constructor will be made private in the future - public static Sha256Hash wrap(byte[] rawHashBytes) { - return new Sha256Hash(rawHashBytes); - } - - public static Sha256Hash wrap(ByteString rawHashByteString) { - return wrap(rawHashByteString.toByteArray()); - } - - /** - * Use {@link #of(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Hash create(boolean isSha256, byte[] contents) { - return of(isSha256, contents); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given file's contents. - * The file contents are read fully into memory, so this method should only be used with small - * files. - * - * @param file the file on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - * @throws IOException if an error occurs while reading the file - */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { - - try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); - } - } - - /** - * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { - return twiceOf(isSha256, contents); - } - - /** - * Creates a new instance containing the hash of the calculated hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (two-time) hash - */ - public static Sha256Hash twiceOf(boolean isSha256, byte[] contents) { - return wrap(hashTwice(isSha256, contents)); - } - - /** - * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the - * checked exception that can never occur with a RuntimeException. - * - * @return a new SHA-256 MessageDigest instance - */ - public static MessageDigest newDigest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); // Can't happen. - } - } - - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - - /** - * Calculates the SHA-256 hash of the given bytes. - * - * @param input the bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - /** - * Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again. - * - * @param input the bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(boolean isSha256, byte[] input) { - return hashTwice(isSha256, input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - } - - /** - * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the - * two ranges and then passing the result to {@link #hashTwice(byte[])}. - */ - public static byte[] hashTwice(boolean isSha256, byte[] input1, int offset1, int length1, - byte[] input2, int offset2, int length2) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = blockHash.getBytes(); - System.arraycopy(numBytes, 0, hash, 0, 8); - return hash; - } - - private byte[] generateBlockId(long blockNum, byte[] blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = blockHash; - System.arraycopy(numBytes, 0, hash, 0, 8); - return hash; - } - - public long getBlockNum() { - return blockNum; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof Sha256Hash)) { - return false; - } - return Arrays.equals(bytes, ((Sha256Hash) o).bytes); - } - - @Override - public String toString() { - return ByteArray.toHexString(bytes); - } - - /** - * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable - * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. - * the value as a big integer lower than the target value). - */ - @Override - public int hashCode() { - // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. - return Ints - .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); - } - - /** - * Returns the bytes interpreted as a positive integer. - */ - public BigInteger toBigInteger() { - return new BigInteger(1, bytes); - } - - /** - * Returns the internal byte array, without defensively copying. Therefore do NOT modify the - * returned array. - */ - public byte[] getBytes() { - return bytes; - } - - /** - * For pb return ByteString. - */ - public ByteString getByteString() { - return ByteString.copyFrom(bytes); - } - - @Override - public int compareTo(final Sha256Hash other) { - for (int i = LENGTH - 1; i >= 0; i--) { - final int thisByte = this.bytes[i] & 0xff; - final int otherByte = other.bytes[i] & 0xff; - if (thisByte > otherByte) { - return 1; - } - if (thisByte < otherByte) { - return -1; - } - } - return 0; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java deleted file mode 100644 index 52290587fc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java +++ /dev/null @@ -1,427 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.netty.util.internal.StringUtil; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import lombok.Getter; -import lombok.Setter; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.IvkDecryptParameters; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import stest.tron.wallet.common.client.Configuration; - -//import org.tron.walletserver.WalletApi; -//import stest.tron.wallet.common.client.Parameter.CommonConstant; - -public class ShieldWrapper { - - private static final String PREFIX_FOLDER = "WalletShield"; - private static final String IVK_AND_NUM_FILE_NAME = PREFIX_FOLDER + "/scanblocknumber"; - private static final String UNSPEND_NOTE_FILE_NAME = PREFIX_FOLDER + "/unspendnote"; - private static final String SPEND_NOTE_FILE_NAME = PREFIX_FOLDER + "/spendnote"; - private static final String SHIELD_ADDRESS_FILE_NAME = PREFIX_FOLDER + "/shieldaddress"; - //private WalletApi wallet; - private static AtomicLong nodeIndex = new AtomicLong(0L); - @Getter - @Setter - public Map ivkMapScanBlockNum = new ConcurrentHashMap(); - @Getter - @Setter - public Map utxoMapNote = new ConcurrentHashMap(); - - //Wallet wallet = new Wallet(); - @Getter - @Setter - public List spendUtxoList = new ArrayList<>(); - @Setter - @Getter - Map shieldAddressInfoMap = new ConcurrentHashMap(); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - private WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - private Thread thread; - @Setter - private boolean resetNote = false; - - /* public void setWallet(WalletApi walletApi) { - wallet = walletApi; - if (!thread.isAlive()) { - thread.start(); - } - }*/ - - private void resetShieldNote() { - ivkMapScanBlockNum.clear(); - for (Entry entry : getShieldAddressInfoMap().entrySet()) { - ivkMapScanBlockNum.put(ByteArray.toHexString(entry.getValue().getIvk()), 0L); - } - - utxoMapNote.clear(); - spendUtxoList.clear(); - - ZenUtils.clearFile(IVK_AND_NUM_FILE_NAME); - ZenUtils.clearFile(UNSPEND_NOTE_FILE_NAME); - ZenUtils.clearFile(SPEND_NOTE_FILE_NAME); - nodeIndex.set(0L); - - updateIvkAndBlockNumFile(); - } - - private void scanBlockByIvk() { - try { - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(-1); - Block block = blockingStubFull.getBlockByNum(builder1.build()); - if (block != null) { - long blockNum = block.getBlockHeader().toBuilder().getRawData().getNumber(); - for (Entry entry : ivkMapScanBlockNum.entrySet()) { - - long start = entry.getValue(); - long end = start; - while (end < blockNum) { - if (blockNum - start > 1000) { - end = start + 1000; - } else { - end = blockNum; - } - - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(start); - builder.setEndBlockIndex(end); - builder.setIvk(ByteString.copyFrom(ByteArray.fromHexString(entry.getKey()))); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - if (notes != null) { - for (int i = 0; i < notes.getNoteTxsList().size(); ++i) { - NoteTx noteTx = notes.getNoteTxsList().get(i); - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.setPaymentAddress(noteTx.getNote().getPaymentAddress()); - noteInfo.setR(noteTx.getNote().getRcm().toByteArray()); - noteInfo.setValue(noteTx.getNote().getValue()); - noteInfo.setTrxId(ByteArray.toHexString(noteTx.getTxid().toByteArray())); - noteInfo.setIndex(noteTx.getIndex()); - noteInfo.setNoteIndex(nodeIndex.getAndIncrement()); - noteInfo.setMemo(noteTx.getNote().getMemo().toByteArray()); - - utxoMapNote.put(noteInfo.getNoteIndex(), noteInfo); - } - saveUnspendNoteToFile(); - } - start = end; - } - - ivkMapScanBlockNum.put(entry.getKey(), blockNum); - } - updateIvkAndBlockNumFile(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void updateNoteWhetherSpend() { - try { - for (Entry entry : utxoMapNote.entrySet()) { - ShieldNoteInfo noteInfo = entry.getValue(); - - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(ByteArray.fromHexString(noteInfo.getTrxId()))); - outPointBuild.setIndex(noteInfo.getIndex()); - request.addOutPoints(outPointBuild.build()); - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull.getMerkleTreeVoucherInfo( - request.build()); - if (merkleVoucherInfo.getVouchersCount() > 0) { - ShieldAddressInfo addressInfo = getShieldAddressInfoMap().get( - noteInfo.getPaymentAddress()); - NoteParameters.Builder builder = NoteParameters.newBuilder(); - builder.setAk(ByteString.copyFrom(addressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(addressInfo.getFullViewingKey().getNk())); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(noteInfo.getPaymentAddress()); - noteBuild.setValue(noteInfo.getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteInfo.getR())); - noteBuild.setMemo(ByteString.copyFrom(noteInfo.getMemo())); - builder.setNote(noteBuild.build()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - - if (result.getResult()) { - spendNote(entry.getKey()); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public boolean init() { - ZenUtils.checkFolderExist(PREFIX_FOLDER); - - loadAddressFromFile(); - loadIvkFromFile(); - loadUnSpendNoteFromFile(); - loadSpendNoteFromFile(); - - thread = new Thread(new scanIvkRunable()); - return true; - } - - /** - * constructor. - */ - public boolean spendNote(long noteIndex) { - ShieldNoteInfo noteInfo = utxoMapNote.get(noteIndex); - if (noteInfo != null) { - utxoMapNote.remove(noteIndex); - spendUtxoList.add(noteInfo); - - saveUnspendNoteToFile(); - saveSpendNoteToFile(noteInfo); - } else { - System.err.println("Find note failure. index:" + noteIndex); - } - return true; - } - - /** - * constructor. - */ - public boolean addNewShieldAddress(final ShieldAddressInfo addressInfo) { - appendAddressInfoToFile(addressInfo); - long blockNum = 0; - try { - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(-1); - Block block = blockingStubFull.getBlockByNum(builder1.build()); - if (block != null) { - blockNum = block.getBlockHeader().toBuilder().getRawData().getNumber(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - ivkMapScanBlockNum.put(ByteArray.toHexString(addressInfo.getIvk()), blockNum); - updateIvkAndBlockNum(ByteArray.toHexString(addressInfo.getIvk()), blockNum); - - return true; - } - - /** - * constructor. - */ - private boolean updateIvkAndBlockNum(final String ivk, long blockNum) { - synchronized (IVK_AND_NUM_FILE_NAME) { - String date = ivk + ";" + blockNum; - ZenUtils.appendToFileTail(IVK_AND_NUM_FILE_NAME, date); - } - return true; - } - - /** - * constructor. - */ - private boolean updateIvkAndBlockNumFile() { - synchronized (IVK_AND_NUM_FILE_NAME) { - ZenUtils.clearFile(IVK_AND_NUM_FILE_NAME); - for (Entry entry : ivkMapScanBlockNum.entrySet()) { - String date = entry.getKey() + ";" + entry.getValue(); - ZenUtils.appendToFileTail(IVK_AND_NUM_FILE_NAME, date); - } - } - return true; - } - - /** - * constructor. - */ - private boolean loadIvkFromFile() { - ivkMapScanBlockNum.clear(); - List list = ZenUtils.getListFromFile(IVK_AND_NUM_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - String[] sourceStrArray = list.get(i).split(";"); - if (sourceStrArray.length != 2) { - System.err.println("len is not right."); - return false; - } - ivkMapScanBlockNum.put(sourceStrArray[0], Long.valueOf(sourceStrArray[1])); - } - return true; - } - - /** - * get shield address list. - */ - public List getShieldAddressList() { - List addressList = new ArrayList<>(); - for (Entry entry : shieldAddressInfoMap.entrySet()) { - addressList.add(entry.getKey()); - } - return addressList; - } - - /** - * update unspend note. - */ - private boolean saveUnspendNoteToFile() { - ZenUtils.clearFile(UNSPEND_NOTE_FILE_NAME); - for (Entry entry : utxoMapNote.entrySet()) { - String date = entry.getValue().encode(); - ZenUtils.appendToFileTail(UNSPEND_NOTE_FILE_NAME, date); - } - return true; - } - - /** - * load unspend note from file. - */ - private boolean loadUnSpendNoteFromFile() { - utxoMapNote.clear(); - - List list = ZenUtils.getListFromFile(UNSPEND_NOTE_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.decode(list.get(i)); - utxoMapNote.put(noteInfo.getNoteIndex(), noteInfo); - - if (noteInfo.getNoteIndex() > nodeIndex.get()) { - nodeIndex.set(noteInfo.getNoteIndex()); - } - } - return true; - } - - /** - * append spend note to file tail. - */ - private boolean saveSpendNoteToFile(ShieldNoteInfo noteInfo) { - String date = noteInfo.encode(); - ZenUtils.appendToFileTail(SPEND_NOTE_FILE_NAME, date); - return true; - } - - /** - * load spend note from file. - */ - private boolean loadSpendNoteFromFile() { - spendUtxoList.clear(); - List list = ZenUtils.getListFromFile(SPEND_NOTE_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.decode(list.get(i)); - spendUtxoList.add(noteInfo); - } - return true; - } - - /** - * load shield address from file. - */ - public boolean loadAddressFromFile() { - List addressList = ZenUtils.getListFromFile(SHIELD_ADDRESS_FILE_NAME); - - shieldAddressInfoMap.clear(); - for (String addressString : addressList) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - if (addressInfo.decode(addressString)) { - shieldAddressInfoMap.put(addressInfo.getAddress(), addressInfo); - } else { - System.out.println("*******************"); - } - } - return true; - } - - /** - * constructor. - */ - public boolean appendAddressInfoToFile(final ShieldAddressInfo addressInfo) { - String shieldAddress = addressInfo.getAddress(); - if (!StringUtil.isNullOrEmpty(shieldAddress)) { - String addressString = addressInfo.encode(); - ZenUtils.appendToFileTail(SHIELD_ADDRESS_FILE_NAME, addressString); - - shieldAddressInfoMap.put(shieldAddress, addressInfo); - } - return true; - } - - /** - * sort by value of UTXO. - */ - public List getvalidateSortUtxoList() { - List> list = new ArrayList<>(utxoMapNote.entrySet()); - Collections.sort(list, (Entry o1, Entry o2) -> { - if (o1.getValue().getValue() < o2.getValue().getValue()) { - return 1; - } else { - return -1; - } - }); - - List utxoList = new ArrayList<>(); - for (Map.Entry entry : list) { - String string = entry.getKey() + " " + entry.getValue().getPaymentAddress() + " "; - string += entry.getValue().getValue(); - string += " "; - string += entry.getValue().getTrxId(); - string += " "; - string += entry.getValue().getIndex(); - string += " "; - string += "UnSpend"; - string += " "; - string += ZenUtils.getMemo(entry.getValue().getMemo()); - utxoList.add(string); - } - return utxoList; - } - - public class scanIvkRunable implements Runnable { - - public void run() { - for (; ; ) { - try { - scanBlockByIvk(); - updateNoteWhetherSpend(); - //wait for 2.5 seconds - for (int i = 0; i < 5; ++i) { - Thread.sleep(500); - if (resetNote) { - resetShieldNote(); - resetNote = false; - System.out.println("Reset shield note success!"); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java deleted file mode 100644 index b1bbf70cc80..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.util.Arrays; -import java.util.Optional; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import org.tron.common.utils.Base58; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.core.zen.address.FullViewingKey; -import org.tron.core.zen.address.IncomingViewingKey; -import org.tron.core.zen.address.KeyIo; -import org.tron.core.zen.address.PaymentAddress; -import org.tron.core.zen.address.SpendingKey; - -@AllArgsConstructor -public class ShieldedAddressInfo { - - @Setter - @Getter - public byte[] sk; - @Setter - @Getter - public byte[] ivk; // 256 - @Setter - @Getter - public byte[] ovk; // 256 - @Setter - @Getter - DiversifierT d; - @Setter - @Getter - byte[] pkD; // 256 - - public ShieldedAddressInfo() { - } - - public FullViewingKey getFullViewingKey() throws ZksnarkException { - SpendingKey spendingKey = new SpendingKey(sk); - return spendingKey.fullViewingKey(); - } - - /** - * check parameters - */ - public boolean validateCheck() { - try { - SpendingKey spendingKey = new SpendingKey(sk); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - if (!Arrays.equals(fullViewingKey.getOvk(), ovk)) { - System.out.println("ovk check failure!"); - return false; - } - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - if (!Arrays.equals(incomingViewingKey.getValue(), ivk)) { - System.out.println("ivk check failure!"); - return false; - } - Optional optionalPaymentAddress = incomingViewingKey.address(d); - if (!optionalPaymentAddress.isPresent() - || !Arrays.equals(optionalPaymentAddress.get().getPkD(), pkD)) { - System.out.println("pkd check failure!"); - return false; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - public String getAddress() { - return getShieldedAddress(d, pkD); - } - - public static String getShieldedAddress(DiversifierT d, byte[] pkD) { - try { - PaymentAddress paymentAddress = new PaymentAddress(d, pkD); - return KeyIo.encodePaymentAddress(paymentAddress); - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - /** - * format shielded address info to a string - */ - public String encode(byte[] encryptKey) throws CipherException { - byte[] text = new byte[sk.length + ivk.length + ovk.length + d.getData().length + pkD.length]; - System.arraycopy(sk, 0, text, 0, sk.length); - System.arraycopy(ivk, 0, text, sk.length, ivk.length); - System.arraycopy(ovk, 0, text, sk.length + ivk.length, ovk.length); - System.arraycopy(d.getData(), 0, text, sk.length + ivk.length + ovk.length, d.getData().length); - System.arraycopy(pkD, 0, text, sk.length + ivk.length + ovk.length + d.getData().length, - pkD.length); - - byte[] cipherText = ZenUtils.aesCtrEncrypt(text, encryptKey); - return Base58.encode(cipherText); - } - - /** - * parse string to get a shielded address info - */ - public boolean decode(final String data, byte[] encryptKey) throws CipherException { - byte[] cipherText = Base58.decode(data); - byte[] text = ZenUtils.aesCtrDecrypt(cipherText, encryptKey); - - sk = Arrays.copyOfRange(text, 0, 32); - ivk = Arrays.copyOfRange(text, 32, 64); - ovk = Arrays.copyOfRange(text, 64, 96); - d = new DiversifierT(Arrays.copyOfRange(text, 96, 107)); - pkD = Arrays.copyOfRange(text, 107, 139); - - if (validateCheck()) { - return true; - } else { - return false; - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java deleted file mode 100644 index 96b38ce06c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java +++ /dev/null @@ -1,96 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import io.netty.util.internal.StringUtil; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; - -@AllArgsConstructor -public class ShieldedTRC20NoteInfo { - - @Setter - @Getter - public long value = 0; - @Setter - @Getter - public String paymentAddress; - @Setter - @Getter - public byte[] r; // 256 - @Setter - @Getter - public String trxId; - @Setter - @Getter - public int index; - @Setter - @Getter - public long noteIndex; - @Setter - @Getter - public long position; - @Setter - @Getter - public byte[] memo; - - public ShieldedTRC20NoteInfo() { - } - - /** - * format shieldedTRC20 note to a string - */ - public String encode(byte[] encryptKey) throws CipherException { - String encodeString = noteIndex + ";"; - encodeString += paymentAddress; - encodeString += ";"; - encodeString += ByteArray.toHexString(r); - encodeString += ";"; - encodeString += trxId; - encodeString += ";"; - encodeString += String.valueOf(value); - encodeString += ";"; - encodeString += String.valueOf(index); - encodeString += ";"; - encodeString += String.valueOf(position); - encodeString += ";"; - String stringMemo = ByteArray.toHexString(memo); - if (StringUtil.isNullOrEmpty(stringMemo)) { - encodeString += "null"; - } else { - encodeString += stringMemo; - } - byte[] chipherText = ZenUtils.aesCtrEncrypt(encodeString.getBytes(), encryptKey); - encodeString = Base58.encode(chipherText); - return encodeString; - } - - /** - * parse string to get shieldedTRC20 note - */ - public boolean decode(String data, byte[] encryptKey) throws CipherException { - byte[] chipherText = Base58.decode(data); - byte[] text = ZenUtils.aesCtrDecrypt(chipherText, encryptKey); - data = new String(text); - - String[] sourceStrArray = data.split(";"); - if (sourceStrArray.length != 8) { - System.out.println("len is not right."); - return false; - } - noteIndex = Long.valueOf(sourceStrArray[0]); - paymentAddress = sourceStrArray[1]; - r = ByteArray.fromHexString(sourceStrArray[2]); - trxId = sourceStrArray[3]; - value = Long.valueOf(sourceStrArray[4]); - index = Integer.valueOf(sourceStrArray[5]); - position = Long.valueOf(sourceStrArray[6]); - if (sourceStrArray[7].equals("null")) { - memo = ByteArray.fromHexString(""); - } else { - memo = ByteArray.fromHexString(sourceStrArray[7]); - } - return true; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java deleted file mode 100644 index ac77484cc2f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java +++ /dev/null @@ -1,1724 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class ZenTrc20Base { - - public final String foundationAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - public static final String zenTrc20TokenOwnerKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTrc20TokenOwnerKey"); - public static final byte[] zenTrc20TokenOwnerAddress = PublicMethed - .getFinalAddress(zenTrc20TokenOwnerKey); - public static final String zenTrc20TokenOwnerAddressString = PublicMethed - .getAddressString(zenTrc20TokenOwnerKey); - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - public com.google.protobuf.ByteString contractAddressByteString; - public static byte[] contractAddressByte; - public static String contractAddress; - public static com.google.protobuf.ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployShieldTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - - - /** - * constructor. - */ - @BeforeSuite(enabled = true, description = "Deploy shield trc20 depend contract") - public void deployShieldTrc20DependContract() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - getDailyBuildStartNum(); - Assert.assertTrue(PublicMethed.sendcoin(zenTrc20TokenOwnerAddress, 10000000000000L, - foundationAccountAddress, foundationAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployShieldTrc20Txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - zenTrc20TokenOwnerKey, zenTrc20TokenOwnerAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTrc20Txid); - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - contractAddressByteString = infoById.get().getContractAddress(); - contractAddressByte = infoById.get().getContractAddress().toByteArray(); - contractAddress = Base58.encode58Check(contractAddressByte); - logger.info(contractAddress); - - contractName = "shield"; - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shield"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_shield"); - data = "\"" + contractAddress + "\"" + "," + scalingFactorLogarithm; - constructorStr = "constructor(address,uint256)"; - deployShieldTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - zenTrc20TokenOwnerKey, zenTrc20TokenOwnerAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTxid); - infoById = PublicMethed - .getTransactionInfoById(deployShieldTxid, blockingStubFull); - shieldAddressByteString = infoById.get().getContractAddress(); - shieldAddressByte = infoById.get().getContractAddress().toByteArray(); - shieldAddress = Base58.encode58Check(shieldAddressByte); - logger.info(shieldAddress); - - data = "\"" + shieldAddress + "\"" + "," + totalSupply.toString(); - String txid = PublicMethed.triggerContract(contractAddressByte, - "approve(address,uint256)", data, false, - 0, maxFeeLimit, zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("approve:" + txid); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - - } - - /** - * constructor. - */ - public void getDailyBuildStartNum() { - DailyBuildReport.startBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder() - .build()).getBlockHeader().getRawData().getNumber(); - System.out.println("!!!!!!! 222222222startnum:" + DailyBuildReport.startBlockNum); - } - - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20Parameters(BigInteger publicFromAmount, - GrpcAPI.DecryptNotesTRC20 inputNoteList, List shieldedAddressInfoList, - List outputNoteList, String publicToAddress, Long pubicToAmount, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20Parameters.Builder builder - = GrpcAPI.PrivateShieldedTRC20Parameters.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - long valueBalance = 0; - - if (inputNoteList != null) { - logger.info("Enter transfer type code"); - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String shieldedAddress = inputNoteList.getNoteTxs(i).getNote().getPaymentAddress(); - - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(0).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - //ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(esk.get().getAsk()); - builder.setNsk(esk.get().getNsk()); - builder.setOvk(esk.get().getOvk()); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(0).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - System.out.println("address " + shieldedAddressInfoList.get(0).getAddress()); - System.out.println("value " + inputNoteList.getNoteTxs(i).getNote().getValue()); - System.out.println("trxId " + inputNoteList.getNoteTxs(i).getTxid()); - System.out.println("index " + inputNoteList.getNoteTxs(i).getIndex()); - System.out.println("position " + inputNoteList.getNoteTxs(i).getPosition()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTrc20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTrc20NoteBuilder.setNote(noteBuild.build()); - spendTrc20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTrc20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTrc20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTrc20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - valueBalance = Math.addExact(valueBalance, inputNoteList.getNoteTxs(i).getNote() - .getValue()); - builder.addShieldedSpends(spendTrc20NoteBuilder.build()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - GrpcAPI.Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - try { - return blockingStubFull.createShieldedContractParameters(builder.build()); - } catch (Exception e) { - Status status = Status.fromThrowable(e); - System.out.println("createShieldedContractParameters failed,error " - + status.getDescription()); - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20ParametersWithoutAsk( - BigInteger publicFromAmount, - GrpcAPI.DecryptNotesTRC20 inputNoteList, List shieldedAddressInfoList, - List outputNoteList, String publicToAddress, byte[] receiverAddressbyte, - Long pubicToAmount, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk.Builder builder - = GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - long valueBalance = 0; - byte[] ask = new byte[32]; - if (inputNoteList != null) { - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(i).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - System.arraycopy(esk.get().getAsk().toByteArray(), 0, ask, 0, 32); - - String ask1 = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask2 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask1))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask2)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - builder.setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))); - builder.setOvk(esk.get().getOvk()); - builder.setNsk(esk.get().getNsk()); - - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(i).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - System.out.println("address " + shieldedAddressInfoList.get(i).getAddress()); - System.out.println("value " + inputNoteList.getNoteTxs(i).getNote().getValue()); - System.out.println("trxId " + ByteArray.toHexString(inputNoteList.getNoteTxs(i) - .getTxid().toByteArray())); - System.out.println("index " + inputNoteList.getNoteTxs(i).getIndex()); - System.out.println("position " + inputNoteList.getNoteTxs(i).getPosition()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTrc20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTrc20NoteBuilder.setNote(noteBuild.build()); - spendTrc20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTrc20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTrc20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTrc20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - builder.addShieldedSpends(spendTrc20NoteBuilder.build()); - valueBalance = Math.addExact(valueBalance, inputNoteList.getNoteTxs(i) - .getNote().getValue()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - GrpcAPI.Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - ShieldedTRC20Parameters parameters = blockingStubFull - .createShieldedContractParametersWithoutAsk(builder.build()); - if (parameters == null) { - System.out.println("createShieldedContractParametersWithoutAsk failed!"); - return null; - } - - GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder stBuilder = - GrpcAPI.ShieldedTRC20TriggerContractParameters.newBuilder(); - stBuilder.setShieldedTRC20Parameters(parameters); - - if (parameters.getParameterType().equals("burn")) { - stBuilder.setAmount(pubicToAmount.toString()); - stBuilder.setTransparentToAddress(ByteString.copyFrom(receiverAddressbyte)); - } - - ByteString messageHash = parameters.getMessageHash(); - List spendDescList = parameters.getSpendDescriptionList(); - ShieldedTRC20Parameters.Builder newBuilder = - ShieldedTRC20Parameters.newBuilder().mergeFrom(parameters); - for (int i = 0; i < spendDescList.size(); i++) { - GrpcAPI.SpendAuthSigParameters.Builder builder1 = GrpcAPI.SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(messageHash); - builder1.setAlpha(builder.build().getShieldedSpends(i).getAlpha()); - - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - newBuilder.getSpendDescriptionBuilder(i) - .setSpendAuthoritySignature( - ByteString.copyFrom(authSig.getValue().toByteArray())); - - stBuilder.addSpendAuthoritySignature(authSig); - BytesMessage triggerInputData; - try { - triggerInputData = blockingStubFull.getTriggerInputForShieldedTRC20Contract(stBuilder - .build()); - } catch (Exception e) { - triggerInputData = null; - System.out.println("getTriggerInputForShieldedTRC20Contract error, please retry!"); - } - if (triggerInputData == null) { - return null; - } - newBuilder.setTriggerContractInput(ByteArray.toHexString(triggerInputData.getValue() - .toByteArray())); - - - } - return newBuilder.build(); - } - - - /** - * constructor. - */ - public String getRootAndPath(long position, WalletSolidityGrpc.WalletSolidityBlockingStub - blockingStubSolidity) { - String methodStr = "getPath(uint256)"; - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - argsStr = "000000000000000000000000000000000000000000000000" + argsStr; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(shieldAddressByte, methodStr, argsStr, - true, 0, 1000000000L, "0", 0, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubSolidity); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - return ByteArray.toHexString(result); - } - - - /** - * constructor. - */ - public String encodeMintParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters, - BigInteger value) { - byte[] mergedBytes; - ShieldContract.ReceiveDescription revDesc = parameters.getReceiveDescription(0); - mergedBytes = ByteUtil.merge( - ByteUtil.bigIntegerToBytes(value, 32), - revDesc.getNoteCommitment().toByteArray(), - revDesc.getValueCommitment().toByteArray(), - revDesc.getEpk().toByteArray(), - revDesc.getZkproof().toByteArray(), - parameters.getBindingSignature().toByteArray(), - revDesc.getCEnc().toByteArray(), - revDesc.getCOut().toByteArray(), - new byte[12] - ); - return ByteArray.toHexString(mergedBytes); - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public Optional getNewShieldedAddress(WalletGrpc.WalletBlockingStub - blockingStubFull) { - ShieldedAddressInfo addressInfo = new ShieldedAddressInfo(); - - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - final Optional d = Optional.of(blockingStubFull.getDiversifier( - EmptyMessage.newBuilder().build())); - - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.get().getAsk()); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(askBuilder.build())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.get().getNsk()); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nskBuilder.build())); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - Optional ivk = Optional.of(blockingStubFull - .getIncomingViewingKey(viewBuilder.build())); - - GrpcAPI.IncomingViewingKeyDiversifierMessage.Builder builder - = GrpcAPI.IncomingViewingKeyDiversifierMessage - .newBuilder(); - builder.setD(d.get()); - builder.setIvk(ivk.get()); - Optional addressMessage = Optional.of(blockingStubFull - .getZenPaymentAddress(builder.build())); - addressInfo.setSk(sk.get().getValue().toByteArray()); - addressInfo.setD(new DiversifierT(d.get().getD().toByteArray())); - addressInfo.setIvk(ivk.get().getIvk().toByteArray()); - addressInfo.setOvk(expandedSpendingKeyMessage.get().getOvk().toByteArray()); - addressInfo.setPkD(addressMessage.get().getPkD().toByteArray()); - - System.out.println("ivk " + ByteArray.toHexString(ivk.get().getIvk().toByteArray())); - System.out.println("ovk " + ByteArray.toHexString(expandedSpendingKeyMessage.get() - .getOvk().toByteArray())); - - return Optional.of(addressInfo); - - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - - /** - * constructor. - */ - public static List addShieldTrc20OutputList(List shieldOutList, - String shieldToAddress, String toAmountString, String menoString, - WalletGrpc.WalletBlockingStub blockingStubFull) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - //noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - noteBuild.setRcm(ByteString.copyFrom(blockingStubFull.getRcm(EmptyMessage.newBuilder().build()) - .getValue().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - - /** - * constructor. - */ - public Long getBalanceOfShieldTrc20(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return Long.parseLong(hexBalance, 16); - } - - - /** - * constructor. - */ - public String getBalanceOfShieldTrc20String(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return hexBalance; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - Long startNum = currentBlockNum - 90L; - final Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - //System.out.println("ak:" + ByteArray.toHexString(ak.get().getValue().toByteArray())); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - //System.out.println("nk:" + ByteArray.toHexString(nk.get().getValue().toByteArray())); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - //ivk.getIvk() - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - String ivkStringOld = ByteArray.toHexString(shieldedAddressInfo.getIvk()); - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - .build(); - try { - return blockingStubSolidity.scanShieldedTRC20NotesByIvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - Long startNum = currentBlockNum - 90L; - final Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - //.setEvents() - .build(); - try { - return blockingStubFull.scanShieldedTRC20NotesByIvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvkWithRange(ShieldedAddressInfo - shieldedAddressInfo, Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - GrpcAPI.DecryptNotesTRC20 result = GrpcAPI.DecryptNotesTRC20.newBuilder().build(); - GrpcAPI.DecryptNotesTRC20 tempNoteTxs; - while (startNum < endNum) { - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(startNum + 99) - .setShieldedTRC20ContractAddress(ByteString - .copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - .build(); - tempNoteTxs = blockingStubFull.scanShieldedTRC20NotesByIvk(parameters); - logger.info("tempNoteTxs size:" + tempNoteTxs.getNoteTxsCount()); - - result = result.toBuilder().addAllNoteTxs(tempNoteTxs.getNoteTxsList()).build(); - - startNum = startNum + 99; - } - try { - return result; - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - Long startNum = currentBlockNum - 90L; - Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String ovkString = ByteArray.toHexString(shieldedAddressInfo.getOvk()); - GrpcAPI.OvkDecryptTRC20Parameters parameters = GrpcAPI.OvkDecryptTRC20Parameters.newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .build(); - - try { - return blockingStubFull.scanShieldedTRC20NotesByOvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByovk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - Long startNum = currentBlockNum - 90L; - Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String ovkString = ByteArray.toHexString(shieldedAddressInfo.getOvk()); - GrpcAPI.OvkDecryptTRC20Parameters parameters = GrpcAPI.OvkDecryptTRC20Parameters.newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .build(); - - try { - return blockingStubSolidity.scanShieldedTRC20NotesByOvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByovk failed,error " + status.getDescription()); - - } - return null; - } - - /** - * constructor. - */ - public static Boolean getTrc20SpendResult( - ShieldedAddressInfo shieldAddressInfo, GrpcAPI.DecryptNotesTRC20.NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - GrpcAPI.NfTRC20Parameters.Builder builder = GrpcAPI.NfTRC20Parameters.newBuilder(); - - String spendingKey = ByteArray.toHexString(shieldAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - builder.setAk(ak.get().getValue()); - builder.setNk(nk.get().getValue()); - builder.setPosition(noteTx.getPosition()); - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(noteTx.getNote().getRcm()); - noteBuild.setMemo(noteTx.getNote().getMemo()); - builder.setNote(noteBuild.build()); - - Optional result = Optional.of(blockingStubFull - .isShieldedTRC20ContractNoteSpent(builder.build())); - return result.get().getIsSpent(); - } - - - /** - * constructor. - */ - public static Boolean getTrc20SpendResult( - ShieldedAddressInfo shieldAddressInfo, GrpcAPI.DecryptNotesTRC20.NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - - GrpcAPI.NfTRC20Parameters.Builder builder = GrpcAPI.NfTRC20Parameters.newBuilder(); - - String spendingKey = ByteArray.toHexString(shieldAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - builder.setAk(ak.get().getValue()); - builder.setNk(nk.get().getValue()); - builder.setPosition(noteTx.getPosition()); - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(noteTx.getNote().getRcm()); - noteBuild.setMemo(noteTx.getNote().getMemo()); - builder.setNote(noteBuild.build()); - - Optional result = Optional.of(blockingStubSolidity - .isShieldedTRC20ContractNoteSpent(builder.build())); - return result.get().getIsSpent(); - } - - - /** - * constructor. - */ - public byte[] getRandomOvk() { - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - return expandedSpendingKeyMessage.get().getOvk().toByteArray(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * constructor. - */ - public BigInteger getRandomAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return BigInteger.valueOf(x); - } - - /** - * constructor. - */ - public Long getRandomLongAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return Long.valueOf(x); - } - - /** - * constructor. - */ - public String encodeTransferParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters) { - byte[] input = new byte[0]; - byte[] spendAuthSig = new byte[0]; - byte[] output = new byte[0]; - byte[] c = new byte[0]; - byte[] bindingSig; - final byte[] mergedBytes; - List spendDescs = parameters.getSpendDescriptionList(); - for (ShieldContract.SpendDescription spendDesc : spendDescs) { - input = ByteUtil.merge(input, - spendDesc.getNullifier().toByteArray(), - spendDesc.getAnchor().toByteArray(), - spendDesc.getValueCommitment().toByteArray(), - spendDesc.getRk().toByteArray(), - spendDesc.getZkproof().toByteArray() - ); - spendAuthSig = ByteUtil.merge( - spendAuthSig, spendDesc.getSpendAuthoritySignature().toByteArray()); - } - byte[] inputOffsetbytes = longTo32Bytes(192); - long spendCount = spendDescs.size(); - byte[] spendCountBytes = longTo32Bytes(spendCount); - byte[] authOffsetBytes = longTo32Bytes(192 + 32 + 320 * spendCount); - List recvDescs = parameters.getReceiveDescriptionList(); - for (ShieldContract.ReceiveDescription recvDesc : recvDescs) { - output = ByteUtil.merge(output, - recvDesc.getNoteCommitment().toByteArray(), - recvDesc.getValueCommitment().toByteArray(), - recvDesc.getEpk().toByteArray(), - recvDesc.getZkproof().toByteArray() - ); - c = ByteUtil.merge(c, - recvDesc.getCEnc().toByteArray(), - recvDesc.getCOut().toByteArray(), - new byte[12] - ); - } - long recvCount = recvDescs.size(); - byte[] recvCountBytes = longTo32Bytes(recvCount); - byte[] outputOffsetbytes = longTo32Bytes(192 + 32 + 320 * spendCount + 32 + 64 * spendCount); - byte[] coffsetBytes = longTo32Bytes(192 + 32 + 320 * spendCount + 32 + 64 * spendCount + 32 - + 288 * recvCount); - bindingSig = parameters.getBindingSignature().toByteArray(); - mergedBytes = ByteUtil.merge(inputOffsetbytes, - authOffsetBytes, - outputOffsetbytes, - bindingSig, - coffsetBytes, - spendCountBytes, - input, - spendCountBytes, - spendAuthSig, - recvCountBytes, - output, - recvCountBytes, - c - ); - return ByteArray.toHexString(mergedBytes); - } - - /** - * constructor. - */ - public String encodeBurnParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters, - BigInteger value, - String transparentToAddress) { - byte[] mergedBytes; - byte[] payTo = new byte[32]; - byte[] transparentToAddressBytes = Commons.decodeFromBase58Check(transparentToAddress); - System.arraycopy(transparentToAddressBytes, 0, payTo, 11, 21); - ShieldContract.SpendDescription spendDesc = parameters.getSpendDescription(0); - mergedBytes = ByteUtil.merge( - spendDesc.getNullifier().toByteArray(), - spendDesc.getAnchor().toByteArray(), - spendDesc.getValueCommitment().toByteArray(), - spendDesc.getRk().toByteArray(), - spendDesc.getZkproof().toByteArray(), - spendDesc.getSpendAuthoritySignature().toByteArray(), - ByteUtil.bigIntegerToBytes(value, 32), - parameters.getBindingSignature().toByteArray(), - payTo - ); - return ByteArray.toHexString(mergedBytes); - } - - - /** - * constructor. - */ - public byte[] longTo32Bytes(long value) { - byte[] longBytes = ByteArray.fromLong(value); - byte[] zeroBytes = new byte[24]; - return ByteUtil.merge(zeroBytes, longBytes); - } - - /** - * constructor. - */ - public JSONArray getHttpShieldedReceivesJsonArray(JSONArray shieldReceives, Long value, - String paymentAddress, String rcm) { - JSONObject note = new JSONObject(); - note.put("value", value); - note.put("payment_address", paymentAddress); - note.put("rcm", rcm); - JSONObject noteIndex = new JSONObject(); - noteIndex.put("note", note); - shieldReceives.add(noteIndex); - return shieldReceives; - - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParameters(String httpNode, Long fromAmount, - JSONObject shieldAccountInfo, JSONArray shiledReceives) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", "4364c875deeb663781a2f1530f9e4f87ea81cc3c757ca2a30fa4768940de2f98"); - rawBody.put("from_amount", fromAmount.toString()); - rawBody.put("shielded_receives", shiledReceives); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("visible", true); - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount) { - return createShieldContractParametersForBurn(httpNode, shieldAccountInfo, shieldedSpends, - toAddress, toAmount, null); - - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount, - JSONArray shieldedReceiver) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - if (shieldedReceiver != null) { - rawBody.put("shielded_receives", shieldedReceiver); - } - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("transparent_to_address", toAddress); - rawBody.put("to_amount", toAmount.toString()); - rawBody.put("visible", true); - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount) { - return createShieldContractParametersWithoutAskForBurn(httpNode, shieldAccountInfo, - shieldedSpends, toAddress, toAmount, null); - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount, - JSONArray shieldedReceiver) { - try { - final String requestUrl - = "http://" + httpNode + "/wallet/createshieldedcontractparameterswithoutask"; - - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ak", shieldAccountInfo.getString("ak")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("transparent_to_address", toAddress); - rawBody.put("to_amount", toAmount.toString()); - rawBody.put("visible", true); - if (shieldedReceiver != null) { - rawBody.put("shielded_receives", shieldedReceiver); - } - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForTransfer(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, JSONArray shieldedReceives) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("shielded_receives", shieldedReceives); - rawBody.put("visible", true); - logger.info(rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForTransfer(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, JSONArray shieldedReceives) { - try { - final String requestUrl = "http://" + httpNode - + "/wallet/createshieldedcontractparameterswithoutask"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ak", shieldAccountInfo.getString("ak")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("shielded_receives", shieldedReceives); - rawBody.put("visible", true); - logger.info(rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static JSONObject createSpendAuthSig(String httpNode, - JSONObject shieldAccountInfo, String messageHash, String alpha) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createspendauthsig"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("tx_hash", messageHash); - rawBody.put("alpha", alpha); - logger.info("createSpendAuthSig:" + rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response); - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvk(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNum(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = "http://" + httpNode + "/wallet/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvkOnSolidity(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNumOnSolidity(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpNode + "/walletsolidity/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvkOnPbft(String httpPbftNode, - JSONObject shieldAddressInfo) { - try { - - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - Long endScanNumber = HttpMethed.parseResponseContent(response).getJSONObject("block_header") - .getJSONObject("raw_data").getLong("number"); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpPbftNode + "/walletpbft/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvk(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNum(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = "http://" + httpNode + "/wallet/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvkOnSolidity(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNumOnSolidity(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpNode + "/walletsolidity/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvkOnPbft(String httpPbftNode, - JSONObject shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - Long endScanNumber = HttpMethed.parseResponseContent(response).getJSONObject("block_header") - .getJSONObject("raw_data").getLong("number"); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpPbftNode + "/walletpbft/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static String getRootAndPathByHttp(String httpNode, Integer position) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - - userBaseObj2.addProperty("owner_address", zenTrc20TokenOwnerAddressString); - userBaseObj2.addProperty("contract_address", shieldAddress); - userBaseObj2.addProperty("function_selector", "getPath(uint256)"); - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - String parameter = "000000000000000000000000000000000000000000000000" + argsStr; - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", maxFeeLimit); - userBaseObj2.addProperty("visible", true); - - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getJSONArray("constant_result").getString(0); - } - - /** - * constructor. - */ - public static JSONArray createAndSetShieldedSpends(String httpNode, - JSONArray shieldedSpends, JSONObject noteTxs) { - JSONObject shieldedSpend = new JSONObject(); - shieldedSpend.put("note", noteTxs.getJSONObject("note")); - shieldedSpend.put("alpha", noteTxs.getJSONObject("note").getString("rcm")); - Integer position = noteTxs.containsKey("position") ? noteTxs.getInteger("position") : 0; - String rootAndPath = getRootAndPathByHttp(httpNode, position); - String root = rootAndPath.substring(0, 64); - String path = rootAndPath.substring(64); - shieldedSpend.put("root", root); - shieldedSpend.put("path", path); - shieldedSpend.put("pos", position); - shieldedSpends.add(shieldedSpend); - return shieldedSpends; - } - - - /** - * constructor. - */ - public static String getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getString("value"); - } - - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpent(String httpNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") - ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpentOnSolidity(String httpNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl - = "http://" + httpNode + "/walletsolidity/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpentOnPbft(String httpPbftNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl - = "http://" + httpPbftNode + "/walletpbft/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static HttpResponse getTriggerInputForShieldedTrc20Contract(String httpNode, - JSONObject shieldedTrc20Parameters, JSONArray spendAuthoritySignature) { - try { - final String requestUrl = "http://" + httpNode - + "/wallet/gettriggerinputforshieldedtrc20contract"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("shielded_TRC20_Parameters", shieldedTrc20Parameters); - userBaseObj2.put("spend_authority_signature", spendAuthoritySignature); - - logger.info("gettriggerinputforshieldedtrc20contract:" + userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTriggerInputForShieldedTrc20BurnContract(String httpNode, - JSONObject shieldedTrc20Parameters, JSONArray spendAuthoritySignature, Long amount, - String toAddress) { - try { - final String requestUrl = "http://" - + httpNode + "/wallet/gettriggerinputforshieldedtrc20contract"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("shielded_TRC20_Parameters", shieldedTrc20Parameters); - userBaseObj2.put("spend_authority_signature", spendAuthoritySignature); - userBaseObj2.put("amount", amount.toString()); - userBaseObj2.put("transparent_to_address", toAddress); - userBaseObj2.put("visible", true); - - logger.info("gettriggerinputforshieldedtrc20contract:" + userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java deleted file mode 100644 index f14b91670b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -public class ZenUtils { - - public static List getListFromFile(final String fileName) { - List list = new ArrayList<>(); - try { - FileInputStream inputStream = new FileInputStream(fileName); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - - String str = null; - while ((str = bufferedReader.readLine()) != null) { - System.out.println(str); - list.add(str); - } - inputStream.close(); - bufferedReader.close(); - } catch (Exception e) { - if (e.getMessage() != null) { - System.out.println(e.getMessage()); - } else { - System.out.println(e.getClass()); - } - } - return list; - } - - public static boolean appendToFileTail(final String fileName, final String content) { - BufferedWriter out = null; - try { - out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true))); - out.write(content + "\n"); - out.flush(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return true; - } - - public static void clearFile(String fileName) { - File file = new File(fileName); - try { - if (file.exists()) { - FileWriter fileWriter = new FileWriter(file); - fileWriter.write(""); - fileWriter.flush(); - fileWriter.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void checkFolderExist(final String filePath) { - try { - File file = new File(filePath); - if (file.exists()) { - if (file.isDirectory()) { - return; - } else { - file.delete(); - } - } - file.mkdir(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static String getMemo(byte[] memo) { - int index = memo.length; - for (; index > 0; --index) { - if (memo[index - 1] != 0) { - break; - } - } - - byte[] inputCheck = new byte[index]; - System.arraycopy(memo, 0, inputCheck, 0, index); - return new String(inputCheck, Charset.forName("UTF-8")); - } - - - public static byte[] aesCtrEncrypt(byte[] text, byte[] encryptKey) throws CipherException { - try { - byte[] iv = new byte[16]; - new SecureRandom().nextBytes(iv); - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - - SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); - byte[] cipherText = cipher.doFinal(text); - byte[] result = new byte[cipherText.length + iv.length]; - System.arraycopy(iv, 0, result, 0, iv.length); - System.arraycopy(cipherText, 0, result, iv.length, cipherText.length); - return result; - } catch (NoSuchPaddingException | NoSuchAlgorithmException - | InvalidAlgorithmParameterException | InvalidKeyException - | BadPaddingException | IllegalBlockSizeException e) { - throw new CipherException("Error performing cipher operation", e); - } - } - - public static byte[] aesCtrDecrypt(byte[] cipherText, byte[] encryptKey) throws CipherException { - try { - byte[] iv = Arrays.copyOfRange(cipherText, 0, 16); - cipherText = Arrays.copyOfRange(cipherText, iv.length, cipherText.length); - - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - - SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(cipherText); - } catch (NoSuchPaddingException | NoSuchAlgorithmException - | InvalidAlgorithmParameterException | InvalidKeyException - | BadPaddingException | IllegalBlockSizeException e) { - throw new CipherException("Error performing cipher operation", e); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java deleted file mode 100644 index a4db9515248..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java +++ /dev/null @@ -1,271 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage002Address = ecKey1.getAddress(); - String linkage002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void updateSetting() { - String sendcoin = PublicMethed - .sendcoinGetTransactionId(linkage002Address, 200000000000L, fromAddress, - testKey002, blockingStubFull); - Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage002Address, 50000000L, - 3, 1, linkage002Key, blockingStubFull)); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage002.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //Set the consumeUserResourcePercent is -1,Nothing change. - byte[] contractAddress; - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, -1, null, linkage002Key, linkage002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - - //Set the consumeUserResourcePercent is 101,Nothing change. - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 101, null, linkage002Key, linkage002Address, blockingStubFull); - Account infoafter3 = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - - Assert.assertEquals(beforeBalance3, afterBalance3); - Assert.assertTrue(afterNetUsed3 == 0); - Assert.assertTrue(afterEnergyUsed3 == 0); - Assert.assertTrue(afterFreeNetUsed3 > 0); - - //Set consumeUserResourcePercent is 100,balance not change,use FreeNet freezeBalanceGetEnergy. - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, linkage002Key, linkage002Address, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 100); - - //Set the consumeUserResourcePercent is 0,balance not change,use FreeNet freezeBalanceGetEnergy. - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, null, linkage002Key, linkage002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter2 = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertEquals(beforeBalance2, afterBalance2); - Assert.assertTrue(afterNetUsed2 == 0); - Assert.assertTrue(afterEnergyUsed2 > 0); - Assert.assertTrue(afterFreeNetUsed2 > 0); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 0); - - //Update the consumeUserResourcePercent setting. - Assert.assertTrue(PublicMethed.updateSetting(contractAddress, 66L, - linkage002Key, linkage002Address, blockingStubFull)); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 66); - - //Updaate the consumeUserResourcePercent setting with -1 and 101 - Assert.assertFalse(PublicMethed.updateSetting(contractAddress, -1L, - linkage002Key, linkage002Address, blockingStubFull)); - Assert.assertFalse(PublicMethed.updateSetting(contractAddress, 101L, - linkage002Key, linkage002Address, blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java deleted file mode 100644 index 1b4d8ad3c65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java +++ /dev/null @@ -1,157 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage003 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage003Address = ecKey1.getAddress(); - String linkage002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployWhenNoEnergy() { - Assert.assertTrue(PublicMethed.sendcoin(linkage003Address, 200000000L, fromAddress, - testKey003, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage003Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage003Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "src/test/resources/soliditycode//contractLinkage003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //use FreeNet and balance,EnergyUsed==0. - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 0, null, linkage002Key, linkage003Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage003Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage003Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getName().isEmpty()); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(afterEnergyUsed == 0L); - Assert.assertTrue(afterFreeNetUsed > 0L); - Assert.assertTrue(afterNetUsed == 0L); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java deleted file mode 100644 index 5cc614e08bc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java +++ /dev/null @@ -1,320 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage004 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - Long currentFee; - Account info; - Long beforeBalance; - Long beforeNetLimit; - Long beforeFreeNetLimit; - Long beforeFreeNetUsed; - Long beforeNetUsed; - Long beforeEnergyLimit; - Long beforeEnergyUsed; - Long afterBalance; - Long afterNetLimit; - Long afterFreeNetLimit; - Long afterFreeNetUsed; - Long afterNetUsed; - Long afterEnergyLimit; - Long afterEnergyUsed; - Long energyUsed; - Long netUsed; - Long energyFee; - Long fee; - Long energyUsageTotal; - Long netFee; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage004Address = ecKey1.getAddress(); - String linkage004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage004Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void test1GetTransactionInfoById() { - ecKey1 = new ECKey(Utils.getRandom()); - linkage004Address = ecKey1.getAddress(); - linkage004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(linkage004Address, 2000000000000L, fromAddress, - testKey003, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(linkage004Address, 10000000L, - 3, linkage004Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyLimit = resourceInfo.getEnergyLimit(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - beforeNetLimit = resourceInfo.getNetLimit(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage004.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - //use freezeBalanceGetNet,Balance .No freezeBalanceGetenergy - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - fee = infoById.get().getFee(); - currentFee = fee; - energyFee = infoById.get().getReceipt().getEnergyFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - afterNetLimit = resourceInfoafter.getNetLimit(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("---------------:"); - Assert.assertTrue(infoById.isPresent()); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - } - - @Test(enabled = true) - public void test2FeeLimitIsTooSmall() { - //When the fee limit is only short with 1 sun,failed.use freezeBalanceGetNet. - maxFeeLimit = currentFee - 1L; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - String filePath = "./src/test/resources/soliditycode/contractLinkage004.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - - Account infoafter1 = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - - Assert.assertTrue((beforeBalance1 - fee1) == afterBalance1); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - Assert.assertTrue(energyUsageTotal1 > 0); - Assert.assertTrue(afterEnergyUsed1 == 0); - Assert.assertTrue(beforeNetUsed1 < afterNetUsed1); - - //When the fee limit is just ok.use energyFee,freezeBalanceGetNet,balance change. - maxFeeLimit = currentFee; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - //logger.info("testFeeLimitIsTooSmall, the txid is " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - Account infoafter2 = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertTrue(infoById2.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue((beforeNetUsed2 + netUsed2) >= afterNetUsed2); - - currentFee = fee2; - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java deleted file mode 100644 index 7fabf396aaf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java +++ /dev/null @@ -1,350 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String contractName; - String code; - String abi; - byte[] contractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage007Address = ecKey1.getAddress(); - String linkage007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true) - public void testRangeOfFeeLimit() { - - //Now the feelimit range is 0-1000000000,including 0 and 1000000000 - Assert.assertTrue(PublicMethed.sendcoin(linkage007Address, 2000000000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - //When the feelimit is large, the deploy will be failed,No used everything. - - String filePath = "./src/test/resources/soliditycode/contractLinkage002.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid; - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit + 1, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterFreeNetUsed == 0); - - Assert.assertTrue(txid == null); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - //When the feelimit is 0, the deploy will be failed.Only use FreeNet,balance not change. - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", 0L, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter1 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - Assert.assertEquals(beforeBalance1, afterBalance1); - Assert.assertTrue(afterFreeNetUsed1 > 0); - Assert.assertTrue(afterNetUsed1 == 0); - Assert.assertTrue(afterEnergyUsed1 == 0); - Optional infoById; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - //Deploy the contract.success.use FreeNet,EnergyFee.balcne change - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - Account infoafter2 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - logger.info("---------------:"); - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue(afterEnergyUsed2 == 0); - Assert.assertTrue(afterFreeNetUsed2 > beforeFreeNetUsed2); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - contractAddress = infoById2.get().getContractAddress().toByteArray(); - - //When the feelimit is large, the trigger will be failed.Only use FreeNetUsed,Balance not change - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - //String initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"63\""; - String num = "4" + "," + "2"; - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 1000, maxFeeLimit + 1, linkage007Address, linkage007Key, blockingStubFull); - Account infoafter3 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - logger.info("---------------:"); - Assert.assertTrue(txid == null); - Assert.assertEquals(beforeBalance3, afterBalance3); - Assert.assertTrue(afterFreeNetUsed3 > beforeNetUsed3); - Assert.assertTrue(afterNetUsed3 == 0); - Assert.assertTrue(afterEnergyUsed3 == 0); - //When the feelimit is 0, the trigger will be failed.Only use FreeNetUsed,Balance not change - AccountResourceMessage resourceInfo4 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info4 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance4 = info4.getBalance(); - Long beforeEnergyLimit4 = resourceInfo4.getEnergyLimit(); - Long beforeEnergyUsed4 = resourceInfo4.getEnergyUsed(); - Long beforeFreeNetLimit4 = resourceInfo4.getFreeNetLimit(); - Long beforeNetLimit4 = resourceInfo4.getNetLimit(); - Long beforeNetUsed4 = resourceInfo4.getNetUsed(); - Long beforeFreeNetUsed4 = resourceInfo4.getFreeNetUsed(); - logger.info("beforeBalance4:" + beforeBalance4); - logger.info("beforeEnergyLimit4:" + beforeEnergyLimit4); - logger.info("beforeEnergyUsed4:" + beforeEnergyUsed4); - logger.info("beforeFreeNetLimit4:" + beforeFreeNetLimit4); - logger.info("beforeNetLimit4:" + beforeNetLimit4); - logger.info("beforeNetUsed4:" + beforeNetUsed4); - logger.info("beforeFreeNetUsed4:" + beforeFreeNetUsed4); - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 1000, maxFeeLimit + 1, linkage007Address, linkage007Key, blockingStubFull); - Account infoafter4 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter4 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance4 = infoafter4.getBalance(); - Long afterEnergyLimit4 = resourceInfoafter4.getEnergyLimit(); - Long afterEnergyUsed4 = resourceInfoafter4.getEnergyUsed(); - Long afterFreeNetLimit4 = resourceInfoafter4.getFreeNetLimit(); - Long afterNetLimit4 = resourceInfoafter4.getNetLimit(); - Long afterNetUsed4 = resourceInfoafter4.getNetUsed(); - Long afterFreeNetUsed4 = resourceInfoafter4.getFreeNetUsed(); - logger.info("afterBalance4:" + afterBalance4); - logger.info("afterEnergyLimit4:" + afterEnergyLimit4); - logger.info("afterEnergyUsed4:" + afterEnergyUsed4); - logger.info("afterFreeNetLimit4:" + afterFreeNetLimit4); - logger.info("afterNetLimit4:" + afterNetLimit4); - logger.info("afterNetUsed4:" + afterNetUsed4); - logger.info("afterFreeNetUsed4:" + afterFreeNetUsed4); - logger.info("---------------:"); - Assert.assertEquals(beforeBalance4, afterBalance4); - Assert.assertTrue(afterFreeNetUsed4 > beforeNetUsed4); - Assert.assertTrue(afterNetUsed4 == 0); - Assert.assertTrue(afterEnergyUsed4 == 0); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(Integer.toString(infoById.get().getResultValue())); - Assert.assertTrue(infoById.get().getFee() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java deleted file mode 100644 index 04d305fd384..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract001Address = ecKey1.getAddress(); - String contract001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployAddressDemo() { - ecKey1 = new ECKey(Utils.getRandom()); - contract001Address = ecKey1.getAddress(); - contract001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract001Key); - - Assert.assertTrue(PublicMethed.sendcoin(contract001Address, 20000000L, toAddress, - testKey003, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract001Address, 15000000L, - 3, 1, contract001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract001Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract001Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/contractScenario001.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract001Key, contract001Address, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - accountResource = PublicMethed.getAccountResource(contract001Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract001Key, blockingStubFull1).getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java deleted file mode 100644 index ae22985e8eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java +++ /dev/null @@ -1,135 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract003Address = ecKey1.getAddress(); - String contract003Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract003Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(contract003Key, blockingStubFull) - .getBalance())); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployErc223() { - ecKey1 = new ECKey(Utils.getRandom()); - contract003Address = ecKey1.getAddress(); - contract003Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract003Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract003Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract003Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/contractScenario003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract003Key, contract003Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - logger.info(txid); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - PublicMethed.waitProduceNextBlock(blockingStubFull1); - accountResource = PublicMethed.getAccountResource(contract003Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract003Address, blockingStubFull1) - .getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - logger.info("transaction fee is " + Long.toString(infoById.get().getFee())); - - Assert.assertTrue(energyLimit == 0); - Assert.assertTrue(energyUsage == 0); - Assert.assertTrue(balanceBefore == balanceAfter + infoById.get().getFee()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java deleted file mode 100644 index 050f4a13a1d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java +++ /dev/null @@ -1,131 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract004Address = ecKey1.getAddress(); - String contract004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract004Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc20TronTokenWithoutData() { - Assert.assertTrue(PublicMethed.sendcoin(contract004Address, 200000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract004Address, 100000000L, - 3, 1, contract004Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract004Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode//contractScenario004.sol"; - String contractName = "TronToken"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract004Key, contract004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - System.out.println(info); - Assert.assertTrue(info.get().getResultValue() == 1); - } - - @Test(enabled = true) - public void deployErc20TronTokenWithData() { - Assert.assertTrue(PublicMethed - .sendcoin(contract004Address, 200000000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract004Address, 100000000L, - 3, 1, contract004Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract004Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode//contractScenario004.sol"; - String contractName = "TronToken"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address)"; - String data = "\"" + Base58.encode58Check(contract004Address) + "\""; - String txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, contract004Key, contract004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - System.out.println(info); - Assert.assertTrue(info.get().getResultValue() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java deleted file mode 100644 index 69821298387..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java +++ /dev/null @@ -1,110 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract005Address = ecKey1.getAddress(); - String contract005Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract005Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false) - public void deployIcoContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract005Address, 200000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract005Address, 10000000L, - 3, 1, contract005Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract005Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario005.sol"; - String contractName = "Crowdsale"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract005Key, contract005Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertEquals(1, infoById.get().getResultValue()); - accountResource = PublicMethed.getAccountResource(contract005Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java deleted file mode 100644 index 78071cc7611..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java +++ /dev/null @@ -1,123 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract006Address = ecKey1.getAddress(); - String contract006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployFomo3D() { - ecKey1 = new ECKey(Utils.getRandom()); - contract006Address = ecKey1.getAddress(); - contract006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract006Key); - - PublicMethed.sendcoin(contract006Address, 2000000000L, toAddress, - testKey003, blockingStubFull); - logger.info(Long.toString(PublicMethed.queryAccount(contract006Key, blockingStubFull) - .getBalance())); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract006Address, 100000000L, - 3, 1, contract006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract006Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario006.sol"; - String contractName = "FoMo3Dlong"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract006Key, contract006Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - accountResource = PublicMethed.getAccountResource(contract006Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java deleted file mode 100644 index 5b85d9e441c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java +++ /dev/null @@ -1,111 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract007Address = ecKey1.getAddress(); - String contract007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc721CardMigration() { - ecKey1 = new ECKey(Utils.getRandom()); - contract007Address = ecKey1.getAddress(); - contract007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(contract007Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract007Address, 100000000L, - 3, 1, contract007Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract007Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(contract007Key, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String contractName = "ERC721Token"; - - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractScenario007_deployErc721CardMigration"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractScenario007_deployErc721CardMigration"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract007Key, contract007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - accountResource = PublicMethed.getAccountResource(contract007Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(contract007Key, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java deleted file mode 100644 index 6fb52760440..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc721CryptoKitties() { - ecKey1 = new ECKey(Utils.getRandom()); - contract008Address = ecKey1.getAddress(); - contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract008Key); - Assert.assertTrue(PublicMethed.sendcoin(contract008Address, 5000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract008Address, 1000000L, - 3, 1, contract008Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - Long shortFeeLimit = 900L; - - String filePath = "./src/test/resources/soliditycode/contractScenario008.sol"; - String contractName = "KittyCore"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", shortFeeLimit, - 0L, 100, null, contract008Key, contract008Address, blockingStubFull); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract008Key, contract008Address, blockingStubFull); - - final SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java deleted file mode 100644 index 4b902d5b404..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java +++ /dev/null @@ -1,126 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract009Address = ecKey1.getAddress(); - String contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract009Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployContainLibraryContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract009Address, 20000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract009Address, 1000000L, - 3, 1, contract009Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract009Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario009.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] libraryContractAddress; - libraryContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract009Key, contract009Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractName = "C"; - retMap = PublicMethed.getBycodeAbiForLibrary(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - String library = retMap.get("library").toString(); - - //String libraryAddress = - // "browser/TvmTest_p1_Grammar_002.sol:Set:" + Base58.encode58Check(libraryContractAddress); - String libraryAddress; - libraryAddress = library - + Base58.encode58Check(libraryContractAddress); - - byte[] contractAddress = PublicMethed - .deployContractForLibrary(contractName, abi, code, "", maxFeeLimit, 0L, 100, libraryAddress, - contract009Key, contract009Address, compilerVersion, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - logger.info(ByteArray.toHexString(smartContract.getContractAddress().toByteArray())); - accountResource = PublicMethed.getAccountResource(contract009Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java deleted file mode 100644 index 58bbc6869bb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario010 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract009Address = ecKey1.getAddress(); - String contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract009Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployContainLibraryContract() { - ecKey1 = new ECKey(Utils.getRandom()); - contract009Address = ecKey1.getAddress(); - contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(contract009Address, 600000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract009Address, 10000000L, - 3, 1, contract009Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract009Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long netUsage = accountResource.getNetUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before Net usage is " + Long.toString(netUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario010.sol"; - String contractName = "TRON_ERC721"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] libraryAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract009Key, contract009Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(libraryAddress, blockingStubFull); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - logger.info(ByteArray.toHexString(smartContract.getContractAddress().toByteArray())); - accountResource = PublicMethed.getAccountResource(contract009Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - netUsage = accountResource.getNetUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after Net usage is " + Long.toString(netUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java deleted file mode 100644 index caa9bb1b3b3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - byte[] contractAddress = null; - String txid = ""; - Optional infoById = null; - String receiveAddressParam; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract012Address = ecKey1.getAddress(); - String contract012Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract012Key); - PublicMethed.printAddress(receiverKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void test1DeployTransactionCoin() { - ecKey1 = new ECKey(Utils.getRandom()); - contract012Address = ecKey1.getAddress(); - contract012Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract012Address, 2000000000L, fromAddress, - testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract012Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario012.sol"; - String contractName = "PayTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100, - null, contract012Key, contract012Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - } - - - @Test(enabled = true) - public void test2TriggerTransactionCoin() { - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - receiveAddressParam = "\"" + Base58.encode58Check(fromAddress) - + "\""; - //When the contract has no money,transaction coin failed. - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 0, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - - @Test(enabled = true) - public void test3TriggerTransactionCanNotCreateAccount() { - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - //Send some trx to the contract account. - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - receiveAddressParam = "\"" + Base58.encode58Check(receiverAddress) - + "\""; - //In smart contract, you can create account - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 1000000000L, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - - Account account2 = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Assert.assertEquals(5L, account2.getBalance()); - - } - - - @Test(enabled = true) - public void test4TriggerTransactionCoin() { - receiveAddressParam = "\"" + Base58.encode58Check(receiverAddress) - + "\""; - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - //This time, trigger the methed sendToAddress2 is OK. - Assert.assertTrue(PublicMethed.sendcoin(receiverAddress, 10000000L, toAddress, - testKey003, blockingStubFull)); - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 0, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java deleted file mode 100644 index d6adab1e7f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress = null; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract013Address = ecKey1.getAddress(); - String contract013Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract013Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployTronTrxAndSunContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract013Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract013Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario013.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract013Key, contract013Address, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - @Test(enabled = true) - public void triggerTronTrxAndSunContract() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract013Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario013.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract013Key, contract013Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - - txid = PublicMethed.triggerContract(contractAddress, - "time()", "#", false, - 0, 100000000L, contract013Address, contract013Key, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java deleted file mode 100644 index 90733f6989e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario014 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("", - ByteArray.toHexString(infoById.get().getResMessage().toByteArray())); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java deleted file mode 100644 index 2ef1504c833..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario015 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function ") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - logger.info("message:" + transaction.getRet(0).getRet()); - logger.info(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - logger.info("Result:" + Hex.toHexString(result)); - logger.info("getCode" + transactionExtention.getResult().getCode().getNumber()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java deleted file mode 100644 index d5784b78778..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java +++ /dev/null @@ -1,193 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.BAD_JUMP_DESTINATION_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario016 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "ContractResult is BAD_JUMP_DESTINATION") - public void test1Grammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "Test"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5061011f8061003a6000396000f30060806040526004361060485763ffffffff7c01000000000000" - + "000000000000000000000000000000000000000000006000350416634ef5a0088114604d5780639093b95b1" - + "4608c575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd" - + "5b50607a60043560b8565b60408051918252519081900360200190f35b348015609757600080fd5b50d3801" - + "560a357600080fd5b50d2801560af57600080fd5b5060b660ee565b005b6000606082604051908082528060" - + "20026020018201604052801560e5578160200160208202803883390190505b50905050919050565b6001805" - + "600a165627a7a7230582092ba162087e13f41c6d6c00ba493edc5a5a6250a3840ece5f99aa38b66366a7000" - + "29"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\"" - + ":\"testOutOfMem\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes32\"}],\"payable\":false" - + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs" - + "\":[],\"name\":\"testBadJumpDestination\",\"outputs\":[],\"payable\":false,\"stateMutab" - + "ility\":\"nonpayable\",\"type\":\"function\"}]"; - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, - "testBadJumpDestination()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), BAD_JUMP_DESTINATION_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.BAD_JUMP_DESTINATION); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert - .assertEquals(contractResult.BAD_JUMP_DESTINATION, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_ENERGY") - public void test2Grammar002() { - - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000001"); - Assert - .assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java deleted file mode 100644 index 6cbcc9b016f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j - -public class GetAccountBalance001 { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey1.getAddress(); - final String testKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Integer sendAmount = 1234; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - Long beforeFromBalance; - Long beforeToBalance; - Long afterFromBalance; - Long afterToBalance; - private final String blackHoleAdd = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Test get account balance") - public void test01GetAccountBalance() { - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - - beforeFromBalance = PublicMethed.getAccountBalance(currentBlock,fromAddress,blockingStubFull); - beforeToBalance = PublicMethed.getAccountBalance(currentBlock,testAddress,blockingStubFull); - - - } - - @Test(enabled = true, description = "Test get block balance") - public void test02GetBlockBalance() { - String txid = PublicMethed.sendcoinGetTransactionId(testAddress, sendAmount, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long blockNum = infoById.get().getBlockNumber(); - - Protocol.Block currentBlock = PublicMethed.getBlock(blockNum,blockingStubFull); - - BlockBalanceTrace blockBalanceTrace - = PublicMethed.getBlockBalance(currentBlock,blockingStubFull); - - - Assert.assertEquals(ByteString.copyFrom(fromAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(0).getAddress()); - Assert.assertEquals(-100000L,blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(0).getAmount()); - - - Assert.assertEquals(ByteString.copyFrom(fromAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(1).getAddress()); - Assert.assertEquals(-sendAmount,blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(1).getAmount()); - - - - Assert.assertEquals(ByteString.copyFrom(testAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(2).getAddress()); - Assert.assertEquals(-sendAmount,-blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(2).getAmount()); - - - afterFromBalance = PublicMethed.getAccountBalance(currentBlock,fromAddress,blockingStubFull); - afterToBalance = PublicMethed.getAccountBalance(currentBlock,testAddress,blockingStubFull); - - Assert.assertTrue(afterToBalance - beforeToBalance == sendAmount); - Assert.assertTrue(beforeFromBalance - afterFromBalance >= sendAmount + 100000L); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(testAddress, testKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java deleted file mode 100644 index 24843f19716..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java +++ /dev/null @@ -1,662 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Commons; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Retry; -import stest.tron.wallet.common.client.utils.Sha256Hash; - - - -@Slf4j - -public class TransactionFee001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey01 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress01 = PublicMethed.getFinalAddress(witnessKey01); - private final String witnessKey02 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress02 = PublicMethed.getFinalAddress(witnessKey02); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private final String blackHoleAdd = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private ManagedChannel channelPbft = null; - - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - final String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - Long startNum = 0L; - Long endNum = 0L; - Long witness01Allowance1 = 0L; - Long witness02Allowance1 = 0L; - Long blackHoleBalance1 = 0L; - Long witness01Allowance2 = 0L; - Long witness02Allowance2 = 0L; - Long blackHoleBalance2 = 0L; - Long witness01Increase = 0L; - Long witness02Increase = 0L; - Long beforeBurnTrxAmount = 0L; - Long afterBurnTrxAmount = 0L; - String txid = null; - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Test deploy contract with energy fee to sr") - public void test01DeployContractEnergyFeeToSr() { - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode//contractLinkage003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = null; - String code = null; - String abi = null; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = PublicMethed.queryAccount(witnessAddress01, blockingStubFull) - .getAllowance(); - witness02Allowance1 = PublicMethed.queryAccount(witnessAddress02, blockingStubFull) - .getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 0, null, - deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = PublicMethed.queryAccount(witnessAddress01, blockingStubFull) - .getAllowance(); - witness02Allowance2 = PublicMethed.queryAccount(witnessAddress02, blockingStubFull) - .getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - //blackHoleIncrease = blackHoleBalance2 - blackHoleBalance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - Map witnessAllowance = PublicMethed.getAllowance2(startNum, endNum, - blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1, blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getFee(),infoById.get().getPackingFee()); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertEquals(beforeBurnTrxAmount,afterBurnTrxAmount); - } - - @Test(enabled = true, retryAnalyzer = Retry.class, - description = "Test update account permission fee to black hole," - + "trans with multi sign and fee to sr") - public void test02UpdateAccountPermissionAndMultiSiginTrans() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - byte[] tmpAddr02 = tmpEcKey02.getAddress(); - final String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey01); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"" - + ",\"threshold\":2," - + "\"operations\"" - + ":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey01) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" - + "]}]}"; - - txid = PublicMethedForMutiSign.accountPermissionUpdateForTransactionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getPackingFee(),0); - Assert.assertEquals(infoById.get().getFee(),100000000L); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - //blackHoleIncrease = blackHoleBalance2 - blackHoleBalance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - logger.info(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000000L); - - - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - - Protocol.Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - logger.info("-----transaction: " + txid); - - Protocol.Transaction transaction1 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray())); - logger.info("-----transaction1: " + txid); - - Protocol.Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, witnessKey01, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - GrpcAPI.TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - witnessAllowance = PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getPackingFee(),0); - Assert.assertEquals(infoById.get().getFee(),1000000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 1000000L); - } - - @Test(enabled = true, description = "Test trigger result is \"OUT_OF_TIME\"" - + " with energy fee to sr") - public void test03OutOfTimeEnergyFeeToBlackHole() { - Random rand = new Random(); - Integer randNum = rand.nextInt(4000); - - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, maxFeeLimit * 10, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = null; - contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "90100", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - logger.info("InfoById:" + infoById); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - Long packingFee = infoById.get().getPackingFee(); - logger.info("receipt:" + infoById.get().getReceipt()); - Assert.assertTrue(packingFee == 0L); - Assert.assertTrue(infoById.get().getFee() >= maxFeeLimit); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == maxFeeLimit); - } - - @Test(enabled = true, description = "Test create account with netFee to sr") - public void test04AccountCreate() { - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - txid = PublicMethed.createAccountGetTxid(fromAddress, lowBalAddress, - testKey002, blockingStubFull); - - - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + " increase :" + witness02Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getPackingFee() == 0L); - Assert.assertTrue(infoById.get().getFee() == 100000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000L); - } - - @Test(enabled = true, description = "Test trigger contract with netFee and energyFee to sr") - public void test05NetFeeAndEnergyFee2Sr() { - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, maxFeeLimit * 10, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = null; - contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, deployKey, deployAddress, blockingStubFull); - for (int i = 0; i < 15; i++) { - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "700", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - } - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "700", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById:" + infoById); - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertEquals(beforeBurnTrxAmount,afterBurnTrxAmount); - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Test create trc10 token with fee not to sr") - public void test06CreateAssetIssue() { - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] tokenAccountAddress = ecKey1.getAddress(); - final String tokenAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - PublicMethed.printAddress(tokenAccountKey); - - Assert.assertTrue(PublicMethed - .sendcoin(tokenAccountAddress, 1028000000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - long now = System.currentTimeMillis(); - long totalSupply = now; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url"; - String name = "AssetIssue016_" + Long.toString(now); - txid = PublicMethed.createAssetIssueGetTxid(tokenAccountAddress, name, name,totalSupply, - 1, 1, start, end, 1, description, url, 0L, - 0L, 1L, 1L, tokenAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + " increase :" + witness02Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getPackingFee() == 0L); - Assert.assertTrue(infoById.get().getFee() == 1024000000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 1024000000L); - - - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Test getburntrx api from solidity or pbft") - public void test07GetBurnTrxFromSolidityOrPbft() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - Assert.assertEquals(blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()),blockingStubSolidity.getBurnTrx( - EmptyMessage.newBuilder().build())); - Assert.assertEquals(blockingStubFull.getBurnTrx(EmptyMessage.newBuilder().build()), - blockingStubPbft.getBurnTrx( - EmptyMessage.newBuilder().build())); - } - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(deployAddress, deployKey, 1, deployAddress, - blockingStubFull); - PublicMethed.freedResource(deployAddress, deployKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java deleted file mode 100644 index c85fdca800b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount012 { - private static final long sendAmount = 10000000000L; - private static final long frozenAmountForTronPower = 3456789L; - private static final long frozenAmountForNet = 7000000L; - private final String foundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress = PublicMethed.getFinalAddress(foundationKey); - - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] frozenAddress = ecKey1.getAddress(); - String frozenKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(frozenKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Freeze balance to get tron power") - public void test01FreezeBalanceGetTronPower() { - - - final Long beforeFrozenTime = System.currentTimeMillis(); - Assert.assertTrue(PublicMethed.sendcoin(frozenAddress, sendAmount, - foundationAddress, foundationKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - final Long beforeTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - final Long beforeTronPowerLimit = accountResource.getTronPowerLimit(); - - - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress,frozenAmountForTronPower, - 0,2,null,frozenKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress,frozenAmountForNet, - 0,0,null,frozenKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterFrozenTime = System.currentTimeMillis(); - Account account = PublicMethed.queryAccount(frozenAddress,blockingStubFull); - Assert.assertEquals(account.getTronPower().getFrozenBalance(),frozenAmountForTronPower); - Assert.assertTrue(account.getTronPower().getExpireTime() > beforeFrozenTime - && account.getTronPower().getExpireTime() < afterFrozenTime); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - Long afterTronPowerLimit = accountResource.getTronPowerLimit(); - Long afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(afterTotalTronPowerWeight - beforeTotalTronPowerWeight, - frozenAmountForTronPower / 1000000L); - - Assert.assertEquals(afterTronPowerLimit - beforeTronPowerLimit, - frozenAmountForTronPower / 1000000L); - - - - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress, - 6000000 - frozenAmountForTronPower, - 0,2,null,frozenKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - afterTronPowerLimit = accountResource.getTronPowerLimit(); - - Assert.assertEquals(afterTronPowerLimit - beforeTronPowerLimit, - 6); - - - } - - - @Test(enabled = true,description = "Vote witness by tron power") - public void test02VotePowerOnlyComeFromTronPower() { - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - final Long beforeTronPowerUsed = accountResource.getTronPowerUsed(); - - - HashMap witnessMap = new HashMap<>(); - witnessMap.put(witnessAddress,frozenAmountForNet / 1000000L); - Assert.assertFalse(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - witnessMap.put(witnessAddress,frozenAmountForTronPower / 1000000L); - Assert.assertTrue(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(afterTronPowerUsed - beforeTronPowerUsed, - frozenAmountForTronPower / 1000000L); - - final Long secondBeforeTronPowerUsed = afterTronPowerUsed; - witnessMap.put(witnessAddress,(frozenAmountForTronPower / 1000000L) - 1); - Assert.assertTrue(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(secondBeforeTronPowerUsed - afterTronPowerUsed, - 1); - - - } - - @Test(enabled = true,description = "Tron power is not allow to others") - public void test03TronPowerIsNotAllowToOthers() { - Assert.assertFalse(PublicMethed.freezeBalanceGetTronPower(frozenAddress, - frozenAmountForTronPower, 0,2, - ByteString.copyFrom(foundationAddress),frozenKey,blockingStubFull)); - } - - - @Test(enabled = true,description = "Unfreeze balance for tron power") - public void test04UnfreezeBalanceForTronPower() { - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(foundationAddress, blockingStubFull); - final Long beforeTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - - - Assert.assertTrue(PublicMethed.unFreezeBalance(frozenAddress,frozenKey,2, - null,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - Assert.assertEquals(beforeTotalTronPowerWeight - afterTotalTronPowerWeight, - 6); - - Assert.assertEquals(accountResource.getTronPowerLimit(),0L); - Assert.assertEquals(accountResource.getTronPowerUsed(),0L); - - Account account = PublicMethed.queryAccount(frozenAddress,blockingStubFull); - Assert.assertEquals(account.getTronPower().getFrozenBalance(),0); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(frozenAddress, frozenKey, 2, null, - blockingStubFull); - PublicMethed.unFreezeBalance(frozenAddress, frozenKey, 0, null, - blockingStubFull); - PublicMethed.freedResource(frozenAddress, frozenKey, foundationAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java deleted file mode 100644 index 03a20ac4aa5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java +++ /dev/null @@ -1,394 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletExchange001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true,description = "Create two asset issue to create exchange") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, toAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true,description = "Test create exchange") - public void test2CreateExchange() { - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethed.exchangeCreate(assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - Integer afterCreateExchangeNum = listExchange.get().getExchangesCount(); - Assert.assertTrue(afterCreateExchangeNum - beforeCreateExchangeNum == 1); - exchangeId = listExchange.get().getExchangesCount(); - - } - - @Test(enabled = true,description = "Test list exchange api") - public void test3ListExchange() { - listExchange = PublicMethed.getExchangeList(blockingStubFull); - for (Integer i = 0; i < listExchange.get().getExchangesCount(); i++) { - Assert.assertFalse(ByteArray.toHexString(listExchange.get().getExchanges(i) - .getCreatorAddress().toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getExchangeId() > 0); - Assert.assertFalse(ByteArray.toStr(listExchange.get().getExchanges(i).getFirstTokenId() - .toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getFirstTokenBalance() > 0); - } - } - - @Test(enabled = true,description = "Test inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethed.injectExchange(exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - } - - @Test(enabled = true,description = "Test withdraw exchange") - public void test5WithdrawExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethed.exchangeWithdraw(exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - - - } - - @Test(enabled = true,description = "Test exchange transaction") - public void test6TransactionExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethed - .exchangeTransaction(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - } - - @Test(enabled = true,description = "Test GetExchangeListPaginated api") - public void test7GetExchangeListPaginated() { - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(100); - ExchangeList exchangeList = blockingStubFull - .getPaginatedExchangeList(pageMessageBuilder.build()); - Assert.assertTrue(exchangeList.getExchangesCount() >= 1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Solidity support getExchangeId - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity); - logger.info("createtime is" + exchangeIdInfo.get().getCreateTime()); - Assert.assertTrue(exchangeIdInfo.get().getCreateTime() > 0); - - //Solidity support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubSolidity); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true,description = "Test get exchange list from pbft") - public void test8GetExchangeListFromPbft() { - //Pbft support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubPbft); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true,description = "Test get exchange by id from pbft") - public void test9GetExchangeByIdFromPbft() { - Assert.assertEquals(PublicMethed.getExchange(exchangeId.toString(), blockingStubPbft), - PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity)); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java deleted file mode 100644 index e11c73c11f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java +++ /dev/null @@ -1,333 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset use Bandwitch") - public void testTransferAssetBandwitchDecreaseWithin10Second() { - //get account - ecKey = new ECKey(Utils.getRandom()); - noBandwitchAddress = ecKey.getAddress(); - noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - PublicMethed.printAddress(noBandwitch); - - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(noBandwitch, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - Assert.assertTrue(transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - noBandwitchAddress, noBandwitch)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer Asset failed when transfer to yourself - Assert.assertFalse(transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - Assert.assertFalse( - transferAsset(fromAddress, assetAccountId.toByteArray(), 9100000000000000000L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is 0 - Assert.assertFalse(transferAsset(fromAddress, assetAccountId.toByteArray(), 0L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is -1 - Assert.assertFalse(transferAsset(fromAddress, assetAccountId.toByteArray(), -1L, - toAddress, testKey003)); - - //Transfer success. - Assert.assertTrue(transferAsset(fromAddress, assetAccountId.toByteArray(), 1L, - toAddress, testKey003)); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(noBandwitchAddress, noBandwitch, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java deleted file mode 100644 index 5dc6e50fd69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java +++ /dev/null @@ -1,346 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "Participate token") - public void testParticipateAssetissue() { - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] participateAccountAddress = ecKey1.getAddress(); - final String participateAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] toAddress = ecKey2.getAddress(); - final String testKey003 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(participateAccountAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Create a new Asset Issue - Assert.assertTrue(PublicMethed.createAssetIssue(participateAccountAddress, - name, totalSupply, 1, 1, System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, 1, description, url, - 2000L, 2000L, 1L, 1L, - participateAccountKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(participateAccountKey, blockingStubFull); - final ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Participate AssetIssue success - logger.info(name); - //Freeze amount to get bandwitch. - logger.info("toaddress balance is " - + PublicMethed.queryAccount(toAddress, blockingStubFull).getBalance()); - Assert.assertTrue(PublicMethed.freezeBalance(toAddress, 10000000, 3, testKey003, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), - 100L, toAddress, testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //The amount is large than the total supply, participate failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), 9100000000000000000L, toAddress, testKey003, - blockingStubFull)); - - //The amount is 0, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), 0L, toAddress, testKey003, blockingStubFull)); - - //The amount is -1, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), -1L, toAddress, testKey003, blockingStubFull)); - - //The asset issue owner address is not correct, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(fromAddress, - assetAccountId.toByteArray(), 100L, - toAddress, testKey003, blockingStubFull)); - - PublicMethed.freedResource(participateAccountAddress, participateAccountKey, fromAddress, - blockingStubFull); - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java deleted file mode 100644 index d27ab4ab55c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java +++ /dev/null @@ -1,416 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private static final String tooLongName = "qazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAssetIssuename = "中文都名字"; - private static final String tooLongAbbreviation = "wazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAbbreviation = "中文的简称"; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset003Address = ecKey.getAddress(); - String asset003Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Create token with exception condition") - public void testExceptionOfAssetIssuew() { - PublicMethed.sendcoin(asset003Address, 2048000000L, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 100000; - Long end = System.currentTimeMillis() + 1000000000; - //Freeze amount is large than total supply, create asset issue failed. - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 9000000000000000000L, 1L, asset003Key, blockingStubFull)); - //Freeze day is 0, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 100L, 0L, asset003Key, blockingStubFull)); - //Freeze amount is 0, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 0L, 1L, asset003Key, blockingStubFull)); - //Freeze day is -1, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 1000L, 1000L, - 1000L, -1L, asset003Key, blockingStubFull)); - //Freeze amount is -1, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - -1L, 1L, asset003Key, blockingStubFull)); - //Freeze day is 3653(10 years + 1 day), create failed - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3653L, asset003Key, blockingStubFull)); - //Start time is late than end time. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - end, start, 2, description, url, 10000L, 10000L, - 1L, 2L, asset003Key, blockingStubFull)); - //Start time is early than currently time. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start - 1000000L, end, 2, description, url, 10000L, - 10000L, 1L, 2L, asset003Key, blockingStubFull)); - //totalSupply is zero. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, 0L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //Total supply is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, -1L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //TrxNum is zero. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 0, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //TrxNum is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, -1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //IcoNum is 0. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 0, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //IcoNum is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, -1, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, "", totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is large than 33 char. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, tooLongName, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is chinese name. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, chineseAssetIssuename, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, "", totalSupply, - 1, 10, start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is large than 33 char. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, tooLongAbbreviation, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is chinese name. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, chineseAbbreviation, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The URL is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, description, "", 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The URL is too long. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, - 1, 10, start, end, 2, description, tooLongUrl, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The description is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, - 1, 10, start, end, 2, "", url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The description is too long, create failed. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, tooLongDescription, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get asset issue list") - public void testGetAllAssetIssue() { - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - Integer times = assetIssueList.getAssetIssueCount(); - if (assetIssueList.getAssetIssueCount() >= 10) { - times = 10; - } - for (Integer j = 0; j < times; j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue"); - } - - //Improve coverage. - assetIssueList.equals(assetIssueList); - assetIssueList.equals(null); - GrpcAPI.AssetIssueList newAssetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - assetIssueList.equals(newAssetIssueList); - assetIssueList.hashCode(); - assetIssueList.getSerializedSize(); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(asset003Address, asset003Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java deleted file mode 100644 index 2b05a13861a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java +++ /dev/null @@ -1,294 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue004 { - - //testng001、testng002、testng003、testng004 - /* private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private static final byte[] NO_ASSET_ADDRESS = Base58 - .decodeFromBase58Check("27XeWZUtufGk8jdjF3m1tuPnnRqqKgzS3pT"); - private static final byte[] INVALID_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue004_" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ByteString addressBs1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBs1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new asset issue - Assert.assertTrue(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 6, 1000, - start, end, 2, description, url, 10000L, 10000L, - 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - } - - } - - @Test(enabled = true, description = "Get asset issue by account") - public void testGetAssetIssueByAccount() { - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueByAccount(request); - Optional queryAssetIssueByAccount = Optional.ofNullable(assetIssueList); - logger.info(Integer.toString(queryAssetIssueByAccount.get().getAssetIssueCount())); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssueCount() == 1); - for (Integer j = 0; j < queryAssetIssueByAccount.get().getAssetIssueCount(); j++) { - if (queryAssetIssueByAccount.get().getAssetIssue(j).getTotalSupply() == totalSupply) { - Assert.assertTrue(queryAssetIssueByAccount.isPresent()); - //Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getDecayRatio() > 0); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getTrxNum() > 0); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getVoteScore() > 0); - Assert.assertFalse(queryAssetIssueByAccount.get().getAssetIssue(j).getUrl().isEmpty()); - logger.info("TestGetAssetIssueByAccount ok!"); - } - } - - //No exception when the address didn't create asset issue. - ByteString addressBS1 = ByteString.copyFrom(NO_ASSET_ADDRESS); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryNoAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(queryNoAssetByAccount.get().getAssetIssueCount() == 0); - logger.info("No asset account queryed nothing"); - - //No exception when the address is invalid. - addressBS1 = ByteString.copyFrom(INVALID_ADDRESS); - request1 = Account.newBuilder().setAddress(addressBS1).build(); - assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - queryNoAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(queryNoAssetByAccount.get().getAssetIssueCount() == 0); - logger.info("No asset account queryed nothing"); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder - frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - Account search = queryAccount(ecKey, blockingStubFull); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java deleted file mode 100644 index 8b7fa37c5c6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java +++ /dev/null @@ -1,297 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue005 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue005_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Get asset issue by name") - public void testGetAssetIssueByName() { - ByteString addressBS1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new asset issue - Assert.assertTrue(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 100, - start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - } - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Get asset issue by name success. - - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(assetAccountId) - .build(); - AssetIssueContract assetIssueByName = - blockingStubFull.getAssetIssueByName(request); - - Assert.assertFalse(assetIssueByName.getUrl().isEmpty()); - Assert.assertFalse(assetIssueByName.getDescription().isEmpty()); - Assert.assertTrue(assetIssueByName.getTotalSupply() > 0); - Assert.assertTrue(assetIssueByName.getTrxNum() > 0); - - //Get asset issue by name failed when the name is not correct.There is no exception. - String wrongName = name + "_wrong"; - ByteString assetNameBs = ByteString.copyFrom(name.getBytes()); - assetNameBs = ByteString.copyFrom(wrongName.getBytes()); - request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertFalse(assetIssueByName.getTotalSupply() > 0); - Assert.assertFalse(assetIssueByName.getTrxNum() > 0); - Assert.assertTrue(assetIssueByName.getUrl().isEmpty()); - Assert.assertTrue(assetIssueByName.getDescription().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java deleted file mode 100644 index 181dac3eddb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java +++ /dev/null @@ -1,213 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue006 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "assetissue006" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "test query assetissue by timestamp from soliditynode"; - String url = "https://testqueryassetissue.com/bytimestamp/from/soliditynode/"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] queryAssetIssueFromSoliAddress = ecKey.getAddress(); - String queryAssetIssueKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /* @Test(enabled = true) - public void testGetAssetIssueListByTimestamp() { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,10000000,3,testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(queryAssetIssueFromSoliAddress,2048000000,fromAddress, - testKey002,blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(queryAssetIssueFromSoliAddress, name, - totalSupply, 1, 100, start, end, 1, description, url, 1000L, - 1000L,1L,1L,queryAssetIssueKey,blockingStubFull)); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage - .newBuilder().build()); - Integer wait = 0; - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 10) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Solidity didn't synchronize the fullnode block,please wait"); - solidityCurrentBlock = blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder() - .build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - - long time = now; - NumberMessage.Builder timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueListByTimestamp(timeStamp.build()); - Optional getAssetIssueListByTimestamp = Optional - .ofNullable(assetIssueList); - - Assert.assertTrue(getAssetIssueListByTimestamp.isPresent()); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() > 0); - logger.info(Integer.toString(getAssetIssueListByTimestamp.get().getAssetIssueCount())); - for (Integer j = 0; j < getAssetIssueListByTimestamp.get().getAssetIssueCount(); j++) { - Assert.assertFalse(getAssetIssueListByTimestamp.get().getAssetIssue(j).getName().isEmpty()); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssue(j).getTotalSupply() > 0); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssue(j).getNum() > 0); - logger.info( - Long.toString(getAssetIssueListByTimestamp.get().getAssetIssue(j).getTotalSupply())); - } - - } - - @Test(enabled = true) - public void testExceptionGetAssetIssueListByTimestamp() { - //Time stamp is below zero. - long time = -1000000000; - NumberMessage.Builder timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueListByTimestamp(timeStamp.build()); - Optional getAssetIssueListByTimestamp = Optional - .ofNullable(assetIssueList); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() == 0); - - //No asset issue was create - time = 1000000000; - timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - assetIssueList = blockingStubSolidity.getAssetIssueListByTimestamp(timeStamp.build()); - getAssetIssueListByTimestamp = Optional.ofNullable(assetIssueList); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() == 0); - - }*/ - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java deleted file mode 100644 index aaac0b4ff29..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java +++ /dev/null @@ -1,173 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue007 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static final Integer trxNum = 1; - private static final Integer icoNum = 1; - private static String name = "AssetIssue007_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset007Address = ecKey1.getAddress(); - String testKeyForAssetIssue007 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String participateAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue007); - PublicMethed.printAddress(participateAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Participate asset issue use participate bandwidth") - public void testParticipateAssetIssueUseParticipateBandwidth() { - Assert.assertTrue(PublicMethed - .sendcoin(asset007Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset007Address, name, totalSupply, trxNum, icoNum, start, end, 1, - description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, - testKeyForAssetIssue007, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(name); - //Assert.assertTrue(PublicMethed.waitProduceNextBlock(blockingStubFull)); - //When no balance, participate an asset issue - Assert.assertFalse(PublicMethed - .participateAssetIssue(asset007Address, name.getBytes(), 1L, participateAssetAddress, - participateAssetCreateKey, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(asset007Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage asset007NetMessage = blockingStubFull.getAccountNet(request); - final Long asset007BeforeFreeNetUsed = asset007NetMessage.getFreeNetUsed(); - - //SendCoin to participate account. - Assert.assertTrue(PublicMethed - .sendcoin(participateAssetAddress, 10000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - addressBs = ByteString.copyFrom(participateAssetAddress); - request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage participateAccountNetMessage = blockingStubFull.getAccountNet(request); - final Long participateAccountBeforeNetUsed = participateAccountNetMessage.getFreeNetUsed(); - Assert.assertTrue(participateAccountBeforeNetUsed == 0); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset007Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info(assetAccountId.toString()); - - //Participate an assetIssue, then query the net information. - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - addressBs = ByteString.copyFrom(asset007Address); - request = Account.newBuilder().setAddress(addressBs).build(); - asset007NetMessage = blockingStubFull.getAccountNet(request); - final Long asset007AfterFreeNetUsed = asset007NetMessage.getFreeNetUsed(); - - addressBs = ByteString.copyFrom(participateAssetAddress); - request = Account.newBuilder().setAddress(addressBs).build(); - participateAccountNetMessage = blockingStubFull.getAccountNet(request); - final Long participateAccountAfterNetUsed = participateAccountNetMessage.getFreeNetUsed(); - - logger.info(Long.toString(asset007BeforeFreeNetUsed)); - logger.info(Long.toString(asset007AfterFreeNetUsed)); - logger.info(Long.toString(participateAccountBeforeNetUsed)); - logger.info(Long.toString(participateAccountAfterNetUsed)); - Assert.assertTrue(asset007AfterFreeNetUsed <= asset007BeforeFreeNetUsed); - Assert.assertTrue(participateAccountAfterNetUsed - participateAccountBeforeNetUsed > 150); - - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account participateInfo = PublicMethed - .queryAccount(participateAssetCreateKey, blockingStubFull); - final Long beforeBalance = participateInfo.getBalance(); - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - participateInfo = PublicMethed.queryAccount(participateAssetCreateKey, blockingStubFull); - final Long afterBalance = participateInfo.getBalance(); - - Assert.assertTrue(beforeBalance - trxNum * 1 * icoNum >= afterBalance); - } - - @AfterMethod - public void aftertest() { - PublicMethed - .freedResource(asset007Address, testKeyForAssetIssue007, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java deleted file mode 100644 index 97ff64d5ca6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue008 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "assetissue008" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "test query assetissue from soliditynode"; - String url = "https://testqueryassetissue.com/from/soliditynode/"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] queryAssetIssueFromSoliAddress = ecKey.getAddress(); - String queryAssetIssueKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Get asset issue list from Solidity") - public void testGetAllAssetIssueFromSolidity() { - Assert.assertTrue(PublicMethed.sendcoin(queryAssetIssueFromSoliAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(queryAssetIssueFromSoliAddress, name, - totalSupply, 1, 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, queryAssetIssueKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(assetIssueList.getAssetIssueCount())); - - if (assetIssueList.getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000L, 3, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 999999L, fromAddress, - testKey002, blockingStubFull)); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info("fullnode block num is " + Long.toString(currentBlock.getBlockHeader() - .getRawData().getNumber())); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - } - - assetIssueList = blockingStubSolidity - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - for (Integer j = 0; j < assetIssueList.getAssetIssueCount(); j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue from solidity"); - } - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(queryAssetIssueFromSoliAddress, queryAssetIssueKey, fromAddress, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java deleted file mode 100644 index 924698b417b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - - /* @Test(enabled = true) - public void testGetAssetIssueByAccountOrNameFromSolidity() { - //By name - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueByAccount(request); - Optional queryAssetIssueByAccount = Optional.ofNullable(assetIssueList); - logger.info(Integer.toString(queryAssetIssueByAccount.get().getAssetIssueCount())); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssueCount() >= 1); - for (Integer j = 0; j < queryAssetIssueByAccount.get().getAssetIssueCount(); j++) { - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getTotalSupply() > 0); - Assert.assertFalse(queryAssetIssueByAccount.get().getAssetIssue(j).getName().isEmpty()); - logger.info("TestGetAssetIssueByAccount in soliditynode ok!!!"); - - } - - //By ID - ByteString assetName = queryAssetIssueByAccount.get().getAssetIssue(0).getName(); - GrpcAPI.BytesMessage requestAsset = GrpcAPI.BytesMessage.newBuilder().setValue(assetName) - .build(); - Contract.AssetIssueContract assetIssueByName = blockingStubSolidity - .getAssetIssueByName(requestAsset); - - Assert.assertFalse(assetIssueByName.getUrl().isEmpty()); - Assert.assertFalse(assetIssueByName.getDescription().isEmpty()); - Assert.assertTrue(assetIssueByName.getTotalSupply() > 0); - Assert.assertTrue(assetIssueByName.getTrxNum() > 0); - - logger.info("TestGetAssetIssueByNameFromSolidity"); - }*/ - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java deleted file mode 100644 index f60dfa834eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java +++ /dev/null @@ -1,443 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue010 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswe" - + "dcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static String name = "testAssetIssue010_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - String updateDescription = "This is test for update asset issue, case AssetIssue_010"; - String updateUrl = "www.updateassetissue.010.cn"; - Long freeAssetNetLimit = 1000L; - Long publicFreeAssetNetLimit = 1000L; - Long updateFreeAssetNetLimit = 10001L; - Long updatePublicFreeAssetNetLimit = 10001L; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset010Address = ecKey.getAddress(); - String testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Update asset issue") - public void testUpdateAssetIssue() { - ecKey = new ECKey(Utils.getRandom()); - asset010Address = ecKey.getAddress(); - testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAssetIssue010); - - Assert.assertTrue(PublicMethed - .sendcoin(asset010Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset010Address, 200000000L, 0, testKeyForAssetIssue010, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(asset010Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 1L, 1L, testKeyForAssetIssue010, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed - .queryAccount(testKeyForAssetIssue010, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Query the description and url,freeAssetNetLimit and publicFreeAssetNetLimit - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder() - .setValue(assetAccountId).build(); - AssetIssueContract assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(description)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(url)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - - //Test update asset issue - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - updatePublicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //After update asset issue ,query the description and url, - // freeAssetNetLimit and publicFreeAssetNetLimit - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(updateDescription)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(updateUrl)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == updateFreeAssetNetLimit); - Assert - .assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == updatePublicFreeAssetNetLimit); - } - - @Test(enabled = true, description = "Update asset issue with exception condition") - public void testUpdateAssetIssueException() { - //Test update asset issue for wrong parameter - //publicFreeAssetNetLimit is -1 - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - -1L, testKeyForAssetIssue010, blockingStubFull)); - //publicFreeAssetNetLimit is 0 - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - 0, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //FreeAssetNetLimit is -1 - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), -1, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //FreeAssetNetLimit is 0 - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), 0, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Description is null - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, "".getBytes(), updateUrl.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Url is null - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, description.getBytes(), "".getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Too long discription - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, tooLongDescription.getBytes(), url.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Too long URL - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, description.getBytes(), tooLongUrl.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - } - - @AfterMethod - public void aftertest() { - PublicMethed - .freedResource(asset010Address, testKeyForAssetIssue010, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset010Address, testKeyForAssetIssue010, 0, asset010Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = PublicMethed.queryAccount(priKey, blockingStubFull); - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java deleted file mode 100644 index c44485f98f9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java +++ /dev/null @@ -1,133 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue011 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String updateMostLongName = Long.toString(now) + "w234567890123456789"; - private static String name = "testAssetIssue011_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset011Address = ecKey1.getAddress(); - String testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetCreateAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue011); - PublicMethed.printAddress(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset to create account") - public void testTransferAssetCreateAccount() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset011Address = ecKey1.getAddress(); - testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetCreateAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset011Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset011Address, 100000000L, 3, testKeyForAssetIssue011, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset011Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue011, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset011Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to create an account. - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetCreateAddress, assetAccountId.toByteArray(), 1L, - asset011Address, testKeyForAssetIssue011, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account queryTransferAssetAccount = PublicMethed - .queryAccount(transferAssetCreateKey, blockingStubFull); - Assert.assertTrue(queryTransferAssetAccount.getAssetV2Count() == 1); - Assert.assertTrue(PublicMethed.updateAccount(asset011Address, Long.toString(now) - .getBytes(), testKeyForAssetIssue011, blockingStubFull)); - Assert.assertTrue(PublicMethed.updateAccount(transferAssetCreateAddress, updateMostLongName - .getBytes(), transferAssetCreateKey, blockingStubFull)); - queryTransferAssetAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Assert.assertFalse(queryTransferAssetAccount.getAccountName().isEmpty()); - PublicMethed - .freedResource(asset011Address, testKeyForAssetIssue011, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset011Address, testKeyForAssetIssue011, 0, asset011Address, - blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java deleted file mode 100644 index 8ad9b6cbe40..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue012 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = "for case assetissue012"; - String url = "https://stest.assetissue012.url"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset012Address = ecKey1.getAddress(); - String testKeyForAssetIssue012 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue012); - logger.info(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset use token owner net") - public void testTransferAssetUseCreatorNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset012Address = ecKey1.getAddress(); - testKeyForAssetIssue012 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(testKeyForAssetIssue012); - PublicMethed.printAddress(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset012Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset012Address, 100000000L, 3, testKeyForAssetIssue012, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset012Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue012, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset012Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed.transferAsset( - transferAssetAddress, assetAccountId.toByteArray(), 10000000L, asset012Address, - testKeyForAssetIssue012, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before transfer asset issue, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset012Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset012Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed > netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed < netCostMeasure); - - PublicMethed - .freedResource(asset012Address, testKeyForAssetIssue012, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset012Address, testKeyForAssetIssue012, 0, asset012Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java deleted file mode 100644 index 58795fda9e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java +++ /dev/null @@ -1,157 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue013 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue013_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 300L; - Long publicFreeAssetNetLimit = 3000L; - String description = "for case assetissue013"; - String url = "https://stest.assetissue013.url"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset013Address = ecKey1.getAddress(); - String testKeyForAssetIssue013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when token owner has no enough net") - public void testWhenNoEnoughFreeAssetNetLimitUseTransferNet() { - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset013Address = ecKey1.getAddress(); - final String testKeyForAssetIssue013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] transferAssetAddress = ecKey2.getAddress(); - final String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - logger.info(testKeyForAssetIssue013); - logger.info(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset013Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset013Address, 100000000L, 3, testKeyForAssetIssue013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset013Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset013Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed.transferAsset( - transferAssetAddress, assetAccountId.toByteArray(), - 10000000L, asset013Address, testKeyForAssetIssue013, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset013Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - assetCreatorNet = PublicMethed - .getAccountNet(asset013Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - - PublicMethed - .freedResource(asset013Address, testKeyForAssetIssue013, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset013Address, testKeyForAssetIssue013, 0, asset013Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java deleted file mode 100644 index 71d1ae22b47..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue014 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue014_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 3000L; - Long publicFreeAssetNetLimit = 300L; - String description = "for case assetissue014"; - String url = "https://stest.assetissue014.url"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset014Address = ecKey1.getAddress(); - String testKeyForAssetIssue014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue014); - logger.info(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when no enough public free asset net") - public void testWhenNoEnoughPublicFreeAssetNetLimitUseTransferNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset014Address = ecKey1.getAddress(); - testKeyForAssetIssue014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset014Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset014Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue014, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset014Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 10000000L, - asset014Address, testKeyForAssetIssue014, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset014Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset014Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - - PublicMethed - .freedResource(asset014Address, testKeyForAssetIssue014, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset014Address, testKeyForAssetIssue014, 0, asset014Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java deleted file mode 100644 index 97dd589f858..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue015 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue015_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue015"; - String url = "https://stest.assetissue015.url"; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset015Address = ecKey1.getAddress(); - String testKeyForAssetIssue015 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey3.getAddress(); - String testKeyForNewAddress = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue015); - logger.info(transferAssetCreateKey); - logger.info(testKeyForNewAddress); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when token owner has not enough bandwidth") - public void atestWhenCreatorHasNoEnoughBandwidthUseTransferNet() { - ecKey1 = new ECKey(Utils.getRandom()); - asset015Address = ecKey1.getAddress(); - testKeyForAssetIssue015 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - newAddress = ecKey3.getAddress(); - testKeyForNewAddress = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset015Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset015Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue015, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset015Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 10000000L, - asset015Address, testKeyForAssetIssue015, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset015Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeFreeNetUsed = assetCreatorNet.getFreeNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeFreeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset015Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterFreeNetUsed = assetCreatorNet.getFreeNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterFreeNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterFreeNetUsed - creatorBeforeFreeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - } - - @Test(enabled = true, description = "Use balance when transfer has not enough net") - public void btestWhenTransferHasNoEnoughBandwidthUseBalance() { - Integer i = 0; - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - while (assetTransferNet.getNetUsed() < 4700 && i++ < 200) { - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - } - - logger.info(Long.toString(assetTransferNet.getFreeNetUsed())); - Assert.assertTrue(assetTransferNet.getFreeNetUsed() >= 4700); - - Assert.assertTrue(PublicMethed.sendcoin(transferAssetAddress, - 20000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Long beforeBalance = transferAccount.getBalance(); - logger.info(Long.toString(beforeBalance)); - - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Long afterBalance = transferAccount.getBalance(); - logger.info(Long.toString(afterBalance)); - - Assert.assertTrue(beforeBalance - afterBalance > 2000); - } - - @Test(enabled = true, description = "Transfer asset use bandwidth when freeze balance") - public void ctestWhenFreezeBalanceUseNet() { - Assert.assertTrue(PublicMethed.freezeBalance(transferAssetAddress, 5000000, - 3, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Account transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - - final Long transferNetUsedBefore = assetTransferNet.getNetUsed(); - final Long transferBalanceBefore = transferAccount.getBalance(); - logger.info("before " + Long.toString(transferBalanceBefore)); - - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - final Long transferNetUsedAfter = assetTransferNet.getNetUsed(); - final Long transferBalanceAfter = transferAccount.getBalance(); - logger.info("after " + Long.toString(transferBalanceAfter)); - - Assert.assertTrue(transferBalanceAfter - transferBalanceBefore == 0); - Assert.assertTrue(transferNetUsedAfter - transferNetUsedBefore > 200); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(asset015Address, testKeyForAssetIssue015, fromAddress, blockingStubFull); - PublicMethed - .freedResource(transferAssetAddress, transferAssetCreateKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java deleted file mode 100644 index d9e6df172e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java +++ /dev/null @@ -1,236 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue016 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue016_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url"; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Get asset issue net resource") - public void test01GetAssetIssueNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(testKeyForAssetIssue016); - PublicMethed.printAddress(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset016Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset016Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue016, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset016Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - AccountNetMessage assetIssueInfo = PublicMethed - .getAccountNet(asset016Address, blockingStubFull); - Assert.assertTrue(assetIssueInfo.getAssetNetLimitCount() == 1); - Assert.assertTrue(assetIssueInfo.getAssetNetUsedCount() == 1); - Assert.assertFalse(assetIssueInfo.getAssetNetLimitMap().isEmpty()); - Assert.assertFalse(assetIssueInfo.getAssetNetUsedMap().isEmpty()); - - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder() - .setValue(assetAccountId).build(); - AssetIssueContract assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() == 0); - assetIssueInfo.hashCode(); - assetIssueInfo.getSerializedSize(); - assetIssueInfo.equals(assetIssueInfo); - - PublicMethed.transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 1000L, - asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() == 0); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetUsage() == 0); - - Assert.assertTrue(PublicMethed.freezeBalance(asset016Address, 30000000L, - 3, testKeyForAssetIssue016, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() > 0); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetUsage() > 150); - - PublicMethed - .freedResource(asset016Address, testKeyForAssetIssue016, fromAddress, blockingStubFull); - - - } - - @Test(enabled = true, description = "Get asset issue by name from Solidity") - public void test02GetAssetIssueByNameFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueByNameFromSolidity(name, - blockingStubSolidity).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue by name from PBFT") - public void test03GetAssetIssueByNameFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueByNameFromSolidity(name, - blockingStubPbft).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue list from PBFT") - public void test04GetAssetIssueListFromPbft() { - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubPbft).get().getAssetIssueCount() >= 1); - } - - - @Test(enabled = true, description = "Get asset issue list from Solidity") - public void test05GetAssetIssueListFromSolidity() { - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubSoliInFull).get().getAssetIssueCount() >= 1); - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubSolidity).get().getAssetIssueCount() >= 1); - } - - @Test(enabled = true, description = "Get asset issue list paginated from PBFT") - public void test06GetAssetIssetListPaginatedFromPbft() { - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubPbft, 0L, 1L).get().getAssetIssueCount() == 1); - } - - - @Test(enabled = true, description = "Get asset issue list paginated from Solidity") - public void test05GetAssetIssueListPaginatedFromSolidity() { - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubSolidity, 0L, 1L).get().getAssetIssueCount() == 1); - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubSoliInFull, 0L, 1L).get().getAssetIssueCount() == 1); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java deleted file mode 100644 index a9a47bc5b4e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java +++ /dev/null @@ -1,225 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue020 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Assetissue020_" + Long.toString(now); - private static final String char33Name = "To_long_asset_name_a" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - Account assetIssue020Account; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset020Address = ecKey1.getAddress(); - String asset020Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset020SecondAddress = ecKey2.getAddress(); - String asset020SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Asset issue support precision") - public void test01AssetIssueSupportPrecision() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset020Address = ecKey1.getAddress(); - asset020Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(asset020Key); - - ecKey2 = new ECKey(Utils.getRandom()); - asset020SecondAddress = ecKey2.getAddress(); - asset020SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(asset020SecondKey); - logger.info(name); - - Assert.assertTrue(PublicMethed.sendcoin(asset020Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(asset020SecondAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 2000000; - Long end = System.currentTimeMillis() + 1000000000; - - //When precision is -1, can not create asset issue - Assert.assertFalse(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, -1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - //When precision is 7, can not create asset issue - Assert.assertFalse(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, 7, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - //When precision is 6, is equal to default. - Assert.assertTrue(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, 6, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset020Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - AssetIssueContractOuterClass.AssetIssueContract assetIssueInfo = PublicMethed - .getAssetIssueByName(name, blockingStubFull); - final Integer preCisionByName = assetIssueInfo.getPrecision(); - final Long TotalSupplyByName = assetIssueInfo.getTotalSupply(); - - assetIssueInfo = PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull); - final Integer preCisionById = assetIssueInfo.getPrecision(); - final Long TotalSupplyById = assetIssueInfo.getTotalSupply(); - - assetIssueInfo = PublicMethed.getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - final Integer preCisionByListName = assetIssueInfo.getPrecision(); - final Long TotalSupplyByListName = assetIssueInfo.getTotalSupply(); - - logger.info("precision is " + preCisionByName); - logger.info("precision is " + preCisionById); - logger.info("precision is " + preCisionByListName); - logger.info("totalsupply is " + TotalSupplyByName); - logger.info("totalsupply is " + TotalSupplyById); - logger.info("totalsupply is " + TotalSupplyByListName); - Assert.assertEquals(preCisionById, preCisionByListName); - Assert.assertEquals(preCisionById, preCisionByName); - Assert.assertEquals(TotalSupplyById, TotalSupplyByListName); - Assert.assertEquals(TotalSupplyById, TotalSupplyByName); - - //When precision is 6, is equal to default. - Assert.assertTrue(PublicMethed.createAssetIssue(asset020SecondAddress, - name, totalSupply, 1, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020SecondKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetIssueInfo = PublicMethed.getAssetIssueByName(name, blockingStubFull); - Assert.assertTrue(assetIssueInfo.getName().isEmpty()); - - } - - @Test(enabled = true, description = "Get asset issue by id from Solidity") - public void test02GetAssetIssueByidFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubSolidity)); - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubSoliInFull)); - } - - @Test(enabled = true, description = "Get asset issue by id from PBFT") - public void test03GetAssetIssueByIdFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubPbft)); - } - - @Test(enabled = true, description = "Get asset issue list by name from Solidity") - public void test04GetAssetIssueListByNameFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueListByNameFromSolidity(name, - blockingStubSolidity).get().getAssetIssueList().get(0).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue list by name from PBFT") - public void test05GetAssetIssueListByNameFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueListByNameFromSolidity(name, - blockingStubPbft).get().getAssetIssue(0).getTotalSupply(), totalSupply); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java deleted file mode 100644 index e7391a1968f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java +++ /dev/null @@ -1,347 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.db.Manager; -import org.tron.protos.Protocol; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue017 { - - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static long start; - private static long end; - private static long now = System.currentTimeMillis(); - private static String name = "AssetIssue017_" + Long.toString(now); - private static long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue017"; - String url = "https://stest.assetissue016.url"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset017Address = ecKey1.getAddress(); - String testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Manager dbManager; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("failed reason is " + ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue017); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void atestGetPaginatedAssetIssueList() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset017Address = ecKey1.getAddress(); - testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset017Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - now = System.currentTimeMillis(); - name = "AssetIssue017_" + Long.toString(now); - totalSupply = now; - Assert.assertTrue(createAssetIssue(asset017Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, - 1L, testKeyForAssetIssue017, blockingStubFull)); - - Integer offset = 0; - Integer limit = 100; - - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - for (Integer i = 0; i < assetIssueListPaginated.get().getAssetIssueCount(); i++) { - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssue(i).getTotalSupply() > 0); - } - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - } - - @Test(enabled = true) - public void btestGetPaginatedAssetIssueListException() { - //offset is 0, limit is 0. - Integer offset = 0; - Integer limit = 0; - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is -1, limit is 100. - offset = -1; - limit = 100; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is -1. - offset = 0; - limit = -1; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is 50. - offset = 0; - limit = 50; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - } - - @Test(enabled = true) - public void ctestGetPaginatedAssetIssueListOnSolidityNode() { - - Integer offset = 0; - Integer limit = 100; - - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - AssetIssueList assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - for (Integer i = 0; i < assetIssueListPaginated.get().getAssetIssueCount(); i++) { - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssue(i).getTotalSupply() > 0); - } - } - - @Test(enabled = true) - public void dtestGetPaginatedAssetIssueListExceptionOnSolidityNode() { - //offset is 0, limit is 0. - Integer offset = 0; - Integer limit = 0; - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is -1. - offset = 0; - limit = -1; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is 50. - offset = 0; - limit = 50; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - - //offset is 0, limit is 1000. - offset = 0; - limit = 1000; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - - //offset is -1, limit is 100. - offset = -1; - limit = 100; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java deleted file mode 100644 index deb877b2444..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java +++ /dev/null @@ -1,238 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue018 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Asset008_" + Long.toString(now); - private static final String char32Name = "To_long_asset_name_" + Long.toString(now); - private static final String char33Name = "To_long_asset_name_a" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] assetAccount1Address = ecKey1.getAddress(); - String assetAccount1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetAccount2Address = ecKey2.getAddress(); - String assetAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] assetAccount3Address = ecKey3.getAddress(); - String assetAccount3Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] assetAccount4Address = ecKey4.getAddress(); - String assetAccount4Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] assetAccount5Address = ecKey5.getAddress(); - String assetAccount5Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - ECKey ecKey6 = new ECKey(Utils.getRandom()); - byte[] assetAccount6Address = ecKey6.getAddress(); - String assetAccount6Key = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(assetAccount1Key); - PublicMethed.printAddress(assetAccount2Key); - PublicMethed.printAddress(assetAccount3Key); - PublicMethed.printAddress(assetAccount4Key); - PublicMethed.printAddress(assetAccount5Key); - PublicMethed.printAddress(assetAccount6Key); - } - - @Test(enabled = true) - public void test1AssetIssueNameBelow32Char() { - - ecKey4 = new ECKey(Utils.getRandom()); - assetAccount4Address = ecKey4.getAddress(); - assetAccount4Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - ecKey5 = new ECKey(Utils.getRandom()); - assetAccount5Address = ecKey5.getAddress(); - assetAccount5Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - ecKey6 = new ECKey(Utils.getRandom()); - assetAccount6Address = ecKey6.getAddress(); - assetAccount6Key = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(assetAccount4Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount5Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount6Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount4Address, - char32Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount4Key, blockingStubFull)); - - //Can't create 33 char token name. - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertFalse(PublicMethed.createAssetIssue(assetAccount5Address, - char33Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount5Key, blockingStubFull)); - - // - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount6Address, - char32Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount6Key, blockingStubFull)); - - } - - @Test(enabled = true) - public void test2SameAssetissueName() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - assetAccount1Address = ecKey1.getAddress(); - assetAccount1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - assetAccount2Address = ecKey2.getAddress(); - assetAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - assetAccount3Address = ecKey3.getAddress(); - assetAccount3Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - logger.info(name); - logger.info("total supply is " + Long.toString(totalSupply)); - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(assetAccount1Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount2Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount3Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create 3 the same name token. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount1Address, - name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount1Key, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount2Address, - name, totalSupply, 2, 2, start, end, 2, description, url, - 3000L, 3000L, 2L, 2L, assetAccount2Key, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount3Address, - name, totalSupply, 3, 3, start, end, 3, description, url, - 4000L, 4000L, 3L, 3L, assetAccount3Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get asset issue by name - String asset1Name = name; - ByteString assetNameBs = ByteString.copyFrom(asset1Name.getBytes()); - - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - Assert.assertTrue(assetIssueList.getAssetIssueCount() == 3); - for (AssetIssueContract assetIssue : assetIssueList.getAssetIssueList()) { - Assert.assertTrue(assetIssue.getTotalSupply() == totalSupply); - - } - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount1Key, blockingStubFull); - final ByteString assetAccount1Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount2Key, blockingStubFull); - final ByteString assetAccount2Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount3Key, blockingStubFull); - final ByteString assetAccount3Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Transfer asset issue. - Assert.assertTrue(PublicMethed.transferAsset(assetAccount2Address, assetAccount1Id - .toByteArray(), 1L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(assetAccount3Address, assetAccount2Id - .toByteArray(), 2L, assetAccount2Address, assetAccount2Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(assetAccount1Address, assetAccount3Id - .toByteArray(), 3L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.transferAsset(assetAccount1Address, assetAccount2Id - .toByteArray(), 3L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Participate asset issue. - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount3Address, assetAccount3Id - .toByteArray(), 1L, assetAccount2Address, assetAccount2Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount1Address, assetAccount1Id - .toByteArray(), 2L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount2Address, assetAccount2Id - .toByteArray(), 3L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.participateAssetIssue(assetAccount2Address, assetAccount3Id - .toByteArray(), 3L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java deleted file mode 100644 index b320b428025..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue019 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset019Address = ecKey1.getAddress(); - String asset019Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset019SecondAddress = ecKey2.getAddress(); - String asset019SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testCanNotCreateTokenNameByTrx() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset019Address = ecKey1.getAddress(); - asset019Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(asset019Key); - - ecKey2 = new ECKey(Utils.getRandom()); - asset019SecondAddress = ecKey2.getAddress(); - asset019SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(asset019SecondKey); - - Assert.assertTrue(PublicMethed.sendcoin(asset019Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(asset019SecondAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 20000000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "trx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TRX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "Trx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "tRx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "trX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TRx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TrX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "tRX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.createAssetIssue(asset019Address, - "trxtrx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.createAssetIssue(asset019SecondAddress, - "_", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019SecondKey, blockingStubFull)); - } - - @Test(enabled = true) - public void testGetAssetLastOperationTimeAndAssetIssueFreeNetUsed() { - Assert.assertTrue(PublicMethed.freezeBalance(asset019Address, 100000000L, 3, - asset019Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(asset019SecondAddress, 100000000L, 3, - asset019SecondKey, blockingStubFull)); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019Address, blockingStubFull); - ByteString asset019AccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019SecondAddress, blockingStubFull); - ByteString asset019SecondAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - PublicMethed.transferAsset(asset019SecondAddress, asset019AccountId.toByteArray(), 100L, - asset019Address, asset019Key, blockingStubFull); - PublicMethed.transferAsset(asset019Address, asset019SecondAccountId.toByteArray(), 100L, - asset019SecondAddress, asset019SecondKey, blockingStubFull); - - PublicMethed.transferAsset(asset019Address, asset019AccountId.toByteArray(), 10L, - asset019SecondAddress, asset019SecondKey, blockingStubFull); - PublicMethed.transferAsset(asset019SecondAddress, asset019SecondAccountId.toByteArray(), - 10L, asset019Address, asset019Key, blockingStubFull); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019Address, blockingStubFull); - for (String id : getAssetIdFromThisAccount.getFreeAssetNetUsageV2Map().keySet()) { - if (asset019SecondAccountId.toStringUtf8().equalsIgnoreCase(id)) { - Assert.assertTrue(getAssetIdFromThisAccount.getFreeAssetNetUsageV2Map().get(id) > 0); - } - } - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019SecondAddress, blockingStubFull); - for (String id : getAssetIdFromThisAccount.getLatestAssetOperationTimeV2Map().keySet()) { - if (asset019AccountId.toStringUtf8().equalsIgnoreCase(id)) { - Assert.assertTrue(getAssetIdFromThisAccount.getLatestAssetOperationTimeV2Map().get(id) > 0); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java deleted file mode 100644 index 56401c66b5f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java +++ /dev/null @@ -1,375 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar001 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Support function type") - public void test1Grammar001() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress = ecKey1.getAddress(); - testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol"; - String contractName = "FunctionSelector"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "true" + "," + "10"; - txid = PublicMethed.triggerContract(contractAddress, - "select(bool,uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray.fromHexString(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 20); - - String num2 = "false" + "," + "10"; - txid = PublicMethed.triggerContract(contractAddress, - "select(bool,uint256)", num2, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional ById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + ById.get().getRet(0)); - logger.info("getNumber:" + ById.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + ById.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + ById.get().getRet(0).getContractRet()); - - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - contractResult.SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), 1); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "0000000000000000000000000000000000000000000000000000000000000064"); - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - logger.info("ById:" + ById); - Assert.assertEquals(ById.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(ById.get().getRet(0).getRetValue(), 0); - - Long returnnumber2 = ByteArray.toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 100); - } - - @Test(enabled = true, description = "Ordinary library contract") - public void test2Grammar002() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "1"; - byte[] contractAddress1 = null; - String filePath1 = "src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol"; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath1, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = library + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "register(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Library contract") - public void test3Grammar003() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "1"; - byte[] contractAddress1 = null; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = library - + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "register(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Extended type") - public void test4Grammar004() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress = ecKey1.getAddress(); - testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol"; - String contractName = "Search"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] contractAddress1 = null; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = null; - libraryAddress = library - + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - String txid = ""; - String num = "1"; - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "append(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String num1 = "0"; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "getData(uint256)", num1, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 1); - - String num2 = "1" + "," + "2"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "replace(uint256,uint256)", num2, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - String txid3 = PublicMethed.triggerContract(contractAddress1, - "getData(uint256)", num1, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber1 == 2); - - } - - @Test(enabled = true, description = "Solidity assembly") - public void test5Grammar006() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol"; - String contractName = "InfoFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String number = "1"; - final String txid1 = PublicMethed.triggerContract(contractAddress, - "f(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid2 = PublicMethed.triggerContract(contractAddress, - "d(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid3 = PublicMethed.triggerContract(contractAddress, - "d1(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid4 = PublicMethed.triggerContract(contractAddress, - "d2(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid5 = PublicMethed.triggerContract(contractAddress, - "d5(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid6 = PublicMethed.triggerContract(contractAddress, - "d4(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid8 = PublicMethed.triggerContract(contractAddress, - "d6(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull1); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertEquals(133,ByteArray.toInt(infoById2.get().getContractResult(0).toByteArray())); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid3, blockingStubFull1); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - Optional infoById4 = PublicMethed - .getTransactionInfoById(txid4, blockingStubFull1); - Assert.assertTrue(infoById4.get().getResultValue() == 0); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(txid5, blockingStubFull1); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - - Optional infoById6 = PublicMethed - .getTransactionInfoById(txid6, blockingStubFull1); - Assert.assertTrue(infoById6.get().getResultValue() == 0); - - Optional infoById8 = PublicMethed - .getTransactionInfoById(txid8, blockingStubFull1); - Assert.assertTrue(infoById8.get().getResultValue() == 0); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java deleted file mode 100644 index 83c9f8e0129..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java +++ /dev/null @@ -1,335 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar002 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress2 = ecKey1.getAddress(); - String testKeyForGrammarAddress2 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress2); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Interface type function") - public void test1Grammar007() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress2, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol"; - String contractName = "Doug"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = ByteArray.toHexString(contractAddress); - String filePath1 = "src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol"; - String contractName1 = "main"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - String code1 = retMap1.get("byteCode").toString() + "0000000000000000000000" - + initParmes; - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - String txid = ""; - String number = "1"; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "dougOfage(uint256)", number, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - String number1 = "687777"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "uintOfName(bytes32)", number1, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull1); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Abstract function") - public void test2Grammar008() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol"; - String contractName = "Cat"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "getContractName()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String returnString = ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(returnString, - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000646656c696e650000000000000000000000000" - + "000000000000000000000000000"); - String txid1 = PublicMethed.triggerContract(contractAddress, - "utterance()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - String returnString1 = ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(returnString1, - "6d69616f77000000000000000000000000000000000000000000000000000000"); - } - - @Test(enabled = true, description = "Gas, value test") - public void test3Grammar010() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol"; - String contractName = "Consumer"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 2000L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "InfoFeed"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "setFeed(address)", initParmes, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress, - "callFeed()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull1); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Call a named function") - public void test4Grammar011() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String number = "1" + "," + "2"; - String txid = PublicMethed.triggerContract(contractAddress, - "f(uint256,uint256)", number, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 1); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "g()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Call a native function") - public void test5Grammar012() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol"; - String contractName = "rTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "info()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Call a Destructor function") - public void test6Grammar013() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 0); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "increment()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Optional infoById2 = null; - String txid2 = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById2.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber1 == 10); - - Optional infoById3 = null; - String txid3 = PublicMethed.triggerContract(contractAddress, - "kill()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - Optional infoById4 = null; - String txid4 = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(txid4 == null); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress2, testKeyForGrammarAddress2, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java deleted file mode 100644 index b3aafd25e88..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java +++ /dev/null @@ -1,522 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar003 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey1.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress3); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Complex structure") - public void test1Grammar014() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress3 = ecKey1.getAddress(); - testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 0); - - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(returnnumber1 == 0); - Optional infoById4 = null; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid4 = PublicMethed.triggerContract(contractAddress, - "callTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById4 = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - - Assert.assertTrue(infoById4.get().getResultValue() == 0); - - String txid5 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById5 = null; - infoById5 = PublicMethed.getTransactionInfoById(txid5, blockingStubFull); - Long returnnumber5 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById5.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber5 == 0); - - String txid6 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById6 = null; - infoById6 = PublicMethed.getTransactionInfoById(txid6, blockingStubFull); - Long returnnumber6 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById6.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber6 == 1); - - String txid7 = PublicMethed.triggerContract(contractAddress, - "callcodeTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById7 = null; - infoById7 = PublicMethed.getTransactionInfoById(txid7, blockingStubFull); - - Assert.assertTrue(infoById7.get().getResultValue() == 0); - - String txid8 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById8 = null; - infoById8 = PublicMethed.getTransactionInfoById(txid8, blockingStubFull); - Long returnnumber8 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById8.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber8 == 1); - - String txid9 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById9 = null; - infoById9 = PublicMethed.getTransactionInfoById(txid9, blockingStubFull); - Long returnnumber9 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById9.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber9 == 1); - - String txid10 = PublicMethed.triggerContract(contractAddress, - "delegatecallTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById10 = null; - infoById10 = PublicMethed.getTransactionInfoById(txid10, blockingStubFull); - - Assert.assertTrue(infoById10.get().getResultValue() == 0); - - String txid11 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById11 = null; - infoById11 = PublicMethed.getTransactionInfoById(txid11, blockingStubFull); - Long returnnumber11 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById11.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber11 == 1); - - String txid12 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById12 = null; - infoById12 = PublicMethed.getTransactionInfoById(txid12, blockingStubFull); - Long returnnumber12 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById12.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber12 == 1); - - String initParmes1 = "\"" + Base58.encode58Check(contractAddress1) + "\""; - String txid13 = PublicMethed.triggerContract(contractAddress, - "callAddTest(address)", initParmes1, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById13 = null; - infoById13 = PublicMethed.getTransactionInfoById(txid13, blockingStubFull); - - Assert.assertTrue(infoById13.get().getResultValue() == 0); - - String txid14 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById14 = null; - infoById14 = PublicMethed.getTransactionInfoById(txid14, blockingStubFull); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById14.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber14 == 1); - - String txid15 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById15 = null; - infoById15 = PublicMethed.getTransactionInfoById(txid15, blockingStubFull); - Long returnnumber15 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById15.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber15 == 3); - } - - - @Test(enabled = true, description = "Fallback function ") - public void test2Grammar015() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol"; - String contractName = "ExecuteFallback"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "callExistFunc()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String i = ByteArray.toHexString(Hash.sha3("ExistFuncCalled(bytes,uint256)".getBytes())); - String resultvalue = ByteArray - .toHexString(infoById.get().getLogList().get(0).getTopicsList().get(0).toByteArray()); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(i, resultvalue); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "callNonExistFunc()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - String value = ByteArray.toHexString(Hash.sha3("FallbackCalled(bytes)".getBytes())); - String resultvalue1 = ByteArray - .toHexString(infoById1.get().getLogList().get(0).getTopicsList().get(0).toByteArray()); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertEquals(value, resultvalue1); - - } - - @Test(enabled = true, description = "Permission control ") - public void test3Grammar016() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "readData()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - String contractName1 = "E"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "g()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Optional infoById2 = null; - String num = "3"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "setData(uint256)", num, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - String txid3 = PublicMethed.triggerContract(contractAddress1, - "getData()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Long returnnumber3 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById3.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber3 == 3); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Structure") - public void test4Grammar017() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol"; - String contractName = "CrowdFunding"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress1 = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - String initParmes = "\"" + Base58.encode58Check(grammarAddress3) + "\",\"1\""; - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress1, - "candidate(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(returnnumber1 == 1); - - String txid1 = PublicMethed.triggerContract(contractAddress1, - "check(uint256)", "1", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - Long returnnumber2 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 1); - - String txid2 = PublicMethed.triggerContract(contractAddress1, - "vote(uint256)", "1", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Built-in function") - public void test5Grammar018() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol"; - String contractName = "Grammar18"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "testAddmod()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 1); - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "testMulmod()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(returnnumber1 == 2); - - String txid2 = PublicMethed.triggerContract(contractAddress, - "testKeccak256()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - String txid3 = PublicMethed.triggerContract(contractAddress, - "testSha256()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - String txid4 = PublicMethed.triggerContract(contractAddress, - "testSha3()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - Optional infoById4 = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById4 = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - Assert.assertTrue(infoById4.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Time unit") - public void test6Grammar019() { - - String filePath = "src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = PublicMethed.triggerContract(contractAddress, - "timetest()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - } - - - @Test(enabled = true, description = "Trx and sun unit conversion.") - public void test7Grammar020() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol"; - String contractName = "trxtest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "test()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java deleted file mode 100644 index ceae3fad717..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java +++ /dev/null @@ -1,638 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.BAD_JUMP_DESTINATION_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_MEMORY_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_TIME_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.STACK_TOO_LARGE_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.STACK_TOO_SMALL_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar004 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "ContractResult is OUT_OF_TIME") - public void test1Grammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - String initParmes = "\"" + "100000" + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testUseCpu(uint256)", initParmes, false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), OUT_OF_TIME_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.OUT_OF_TIME); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.OUT_OF_TIME, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_MEMORY") - public void test2Grammar002() { - String filePath = "./src/test/resources/soliditycode/testOutOfMem.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - String initParmes = "\"" + "31457280" + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testOutOfMem(uint256)", initParmes, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), OUT_OF_MEMORY_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.OUT_OF_MEMORY); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.OUT_OF_MEMORY, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is BAD_JUMP_DESTINATION") - public void test3Grammar003() { - String contractName = "Test"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5061011f8061003a6000396000f30060806040526004361060485763ffffffff7c01000000000000" - + "000000000000000000000000000000000000000000006000350416634ef5a0088114604d5780639093b95b1" - + "4608c575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd" - + "5b50607a60043560b8565b60408051918252519081900360200190f35b348015609757600080fd5b50d3801" - + "560a357600080fd5b50d2801560af57600080fd5b5060b660ee565b005b6000606082604051908082528060" - + "20026020018201604052801560e5578160200160208202803883390190505b50905050919050565b6001805" - + "600a165627a7a7230582092ba162087e13f41c6d6c00ba493edc5a5a6250a3840ece5f99aa38b66366a7000" - + "29"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\"" - + ":\"testOutOfMem\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes32\"}],\"payable\":false" - + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs" - + "\":[],\"name\":\"testBadJumpDestination\",\"outputs\":[],\"payable\":false,\"stateMutab" - + "ility\":\"nonpayable\",\"type\":\"function\"}]"; - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - txid = PublicMethed - .triggerContract(contractAddress, "testBadJumpDestination()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), BAD_JUMP_DESTINATION_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.BAD_JUMP_DESTINATION); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert - .assertEquals(contractResult.BAD_JUMP_DESTINATION, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_ENERGY") - public void test4Grammar004() { - - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 20L, 100, - null, testKeyForGrammarAddress, grammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert.assertEquals(ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000001"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - } - - - @Test(enabled = true, description = "ContractResult is ILLEGAL_OPERATION") - public void test5Grammar005() { - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "4" + "," + "0"; - - txid = PublicMethed - .triggerContract(contractAddress, "divideIHaveArgsReturn(int256,int256)", num, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000012"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - } - - - @Test(enabled = true, description = "ContractResult is REVERT") - public void test6Grammar006() { - - String filePath = - "src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testRequire()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "ContractResult is SUCCESS") - public void test7Grammar007() { - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "4" + "," + "2"; - - txid = PublicMethed - .triggerContract(contractAddress, "divideIHaveArgsReturn(int256,int256)", num, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), - contractResult.SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), contractResult.SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "0000000000000000000000000000000000000000000000000000000000000002"); - - } - - - @Test(enabled = true, description = "ContractResult is TRANSFER_FAILED") - public void test8Grammar008() { - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(grammarAddress, blockingStubFull); - info = PublicMethed.queryAccount(testKeyForGrammarAddress, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testTransferTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(testKeyForGrammarAddress, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(grammarAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info( - "infoById.get().getReceipt().getResult(): " + infoById.get().getReceipt().getResult()); - logger.info("ByteArray.toStr(infoById.get().getResMessage().toByteArray()): " + ByteArray - .toStr(infoById.get().getResMessage().toByteArray())); - /*Assert.assertEquals( - "transfer trx failed: Validate InternalTransfer error, no ToAccount." - + " And not allowed to create account in smart contract.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray()));*/ - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "ContractResult is STACK_TOO_SMALL") - public void test9Grammar009() { - - String contractName = "TestThrowsContract"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testStackTooSmall\",\"outputs\":[]" - + ",\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"}]"; - String code = "60606040523415600b57fe5b5b60608060196000396000f300606060405263ffffffff60e060020" - + "a6000350416632f3a24cc81146020575bfe5b3415602757fe5b602d602f565b005b50505b5600a165627a7a" - + "723058208184f2ff2627a8a490bfd1233a891f2f4605375d0fec375e237ffc188cdd7ec70029"; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testStackTooSmall()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), STACK_TOO_SMALL_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), STACK_TOO_SMALL_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.STACK_TOO_SMALL); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.STACK_TOO_SMALL, infoById.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "ContractResult is STACK_TOO_LARGE") - public void test9Grammar010() { - - String contractName = "TestThrowsContract"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testStackTooLarge\",\"outputs\":[]" - + ",\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"}]"; - String code = "6060604052341561000c57fe5b5b610b658061001c6000396000f300606060405263ffffffff60e" - + "060020a600035041663f7d9c5c68114610021575bfe5b341561002957fe5b610031610033565b005b600060" - + "0160026003600460056006600760086009600a600b600c600d600e600f60106011601260136014601560166" - + "01760186019601a601b601c601d601e601f6020602160226023602460256026602760286029602a602b602c" - + "602d602e602f6030603160326033603460356036603760386039603a603b603c603d603e603f60406041604" - + "26043604460456046604760486049604a604b604c604d604e604f6050605160526053605460556056605760" - + "586059605a605b605c605d605e605f6060606160626063606460656066606760686069606a606b606c606d6" - + "06e606f6070607160726073607460756076607760786079607a607b607c607d607e607f6080608160826083" - + "608460856086608760886089608a608b608c608d608e608f609060916092609360946095609660976098609" - + "9609a609b609c609d609e609f60a060a160a260a360a460a560a660a760a860a960aa60ab60ac60ad60ae60" - + "af60b060b160b260b360b460b560b660b760b860b960ba60bb60bc60bd60be60bf60c060c160c260c360c46" - + "0c560c660c760c860c960ca60cb60cc60cd60ce60cf60d060d160d260d360d460d560d660d760d860d960da" - + "60db60dc60dd60de60df60e060e160e260e360e460e560e660e760e860e960ea60eb60ec60ed60ee60ef60f" - + "060f160f260f360f460f560f660f760f860f960fa60fb60fc60fd60fe60ff61010061010161010261010361" - + "010461010561010661010761010861010961010a61010b61010c61010d61010e61010f61011061011161011" - + "261011361011461011561011661011761011861011961011a61011b61011c61011d61011e61011f61012061" - + "012161012261012361012461012561012661012761012861012961012a61012b61012c61012d61012e61012" - + "f61013061013161013261013361013461013561013661013761013861013961013a61013b61013c61013d61" - + "013e61013f61014061014161014261014361014461014561014661014761014861014961014a61014b61014" - + "c61014d61014e61014f61015061015161015261015361015461015561015661015761015861015961015a61" - + "015b61015c61015d61015e61015f61016061016161016261016361016461016561016661016761016861016" - + "961016a61016b61016c61016d61016e61016f61017061017161017261017361017461017561017661017761" - + "017861017961017a61017b61017c61017d61017e61017f61018061018161018261018361018461018561018" - + "661018761018861018961018a61018b61018c61018d61018e61018f61019061019161019261019361019461" - + "019561019661019761019861019961019a61019b61019c61019d61019e61019f6101a06101a16101a26101a" - + "36101a46101a56101a66101a76101a86101a96101aa6101ab6101ac6101ad6101ae6101af6101b06101b161" - + "01b26101b36101b46101b56101b66101b76101b86101b96101ba6101bb6101bc6101bd6101be6101bf6101c" - + "06101c16101c26101c36101c46101c56101c66101c76101c86101c96101ca6101cb6101cc6101cd6101ce61" - + "01cf6101d06101d16101d26101d36101d46101d56101d66101d76101d86101d96101da6101db6101dc6101d" - + "d6101de6101df6101e06101e16101e26101e36101e46101e56101e66101e76101e86101e96101ea6101eb61" - + "01ec6101ed6101ee6101ef6101f06101f16101f26101f36101f46101f56101f66101f76101f86101f96101f" - + "a6101fb6101fc6101fd6101fe6101ff61020061020161020261020361020461020561020661020761020861" - + "020961020a61020b61020c61020d61020e61020f61021061021161021261021361021461021561021661021" - + "761021861021961021a61021b61021c61021d61021e61021f61022061022161022261022361022461022561" - + "022661022761022861022961022a61022b61022c61022d61022e61022f61023061023161023261023361023" - + "461023561023661023761023861023961023a61023b61023c61023d61023e61023f61024061024161024261" - + "024361024461024561024661024761024861024961024a61024b61024c61024d61024e61024f61025061025" - + "161025261025361025461025561025661025761025861025961025a61025b61025c61025d61025e61025f61" - + "026061026161026261026361026461026561026661026761026861026961026a61026b61026c61026d61026" - + "e61026f61027061027161027261027361027461027561027661027761027861027961027a61027b61027c61" - + "027d61027e61027f61028061028161028261028361028461028561028661028761028861028961028a61028" - + "b61028c61028d61028e61028f61029061029161029261029361029461029561029661029761029861029961" - + "029a61029b61029c61029d61029e61029f6102a06102a16102a26102a36102a46102a56102a66102a76102a" - + "86102a96102aa6102ab6102ac6102ad6102ae6102af6102b06102b16102b26102b36102b46102b56102b661" - + "02b76102b86102b96102ba6102bb6102bc6102bd6102be6102bf6102c06102c16102c26102c36102c46102c" - + "56102c66102c76102c86102c96102ca6102cb6102cc6102cd6102ce6102cf6102d06102d16102d26102d361" - + "02d46102d56102d66102d76102d86102d96102da6102db6102dc6102dd6102de6102df6102e06102e16102e" - + "26102e36102e46102e56102e66102e76102e86102e96102ea6102eb6102ec6102ed6102ee6102ef6102f061" - + "02f16102f26102f36102f46102f56102f66102f76102f86102f96102fa6102fb6102fc6102fd6102fe6102f" - + "f61030061030161030261030361030461030561030661030761030861030961030a61030b61030c61030d61" - + "030e61030f61031061031161031261031361031461031561031661031761031861031961031a61031b61031" - + "c61031d61031e61031f61032061032161032261032361032461032561032661032761032861032961032a61" - + "032b61032c61032d61032e61032f61033061033161033261033361033461033561033661033761033861033" - + "961033a61033b61033c61033d61033e61033f61034061034161034261034361034461034561034661034761" - + "034861034961034a61034b61034c61034d61034e61034f61035061035161035261035361035461035561035" - + "661035761035861035961035a61035b61035c61035d61035e61035f61036061036161036261036361036461" - + "036561036661036761036861036961036a61036b61036c61036d61036e61036f61037061037161037261037" - + "361037461037561037661037761037861037961037a61037b61037c61037d61037e61037f61038061038161" - + "038261038361038461038561038661038761038861038961038a61038b61038c61038d61038e61038f61039" - + "061039161039261039361039461039561039661039761039861039961039a61039b61039c61039d61039e61" - + "039f6103a06103a16103a26103a36103a46103a56103a66103a76103a86103a96103aa6103ab6103ac6103a" - + "d6103ae6103af6103b06103b16103b26103b36103b46103b56103b66103b76103b86103b96103ba6103bb61" - + "03bc6103bd6103be6103bf6103c06103c16103c26103c36103c46103c56103c66103c76103c86103c96103c" - + "a6103cb6103cc6103cd6103ce6103cf6103d06103d16103d26103d36103d46103d56103d66103d76103d861" - + "03d96103da6103db6103dc6103dd6103de6103df6103e06103e16103e26103e36103e46103e56103e66103e" - + "76103e86103e96103ea6103eb6103ec6103ed6103ee6103ef6103f06103f16103f26103f36103f46103f561" - + "03f66103f76103f86103f96103fa6103fb6103fc6103fd6103fe6103ff6104005b5600a165627a7a7230582" - + "0998f09cc267db91352a3d0a4ab60ea08fc306fa8bc6dd78dc324a06109dcf0420029"; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testStackTooLarge()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), STACK_TOO_LARGE_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), STACK_TOO_LARGE_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.STACK_TOO_LARGE); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.STACK_TOO_LARGE, infoById.get().getReceipt().getResult()); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java deleted file mode 100644 index 59baee113a2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java +++ /dev/null @@ -1,316 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MarketSellAsset001 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final String foundationKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = - Configuration.getByPath("testng.conf").getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - public String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - - /** constructor. */ - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(solidityNode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress001, - 20000_000000L, - foundationAddress001, - foundationKey001, - blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress002, - 20000_000000L, - foundationAddress001, - foundationKey001, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue( - PublicMethed.createAssetIssue( - testAddress001, - name, - 10000_000000L, - 1, - 1, - start, - end, - 1, - description, - url, - 10000L, - 10000L, - 1L, - 1L, - testKey001, - blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue( - PublicMethed.createAssetIssue( - testAddress002, - name, - 10000_000000L, - 1, - 1, - start, - end, - 1, - description, - url, - 10000L, - 10000L, - 1L, - 1L, - testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = - PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID() - .toByteArray(); - - assetAccountId002 = - PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID() - .toByteArray(); - } - - @Test(enabled = true, description = "create sellOrder") - void marketSellAssetTest001() { - - String txid = - PublicMethed.marketSellAsset( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed.getTransactionById(txid, blockingStubFull); - - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = - PublicMethed.getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed.getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional transactionFromSolidity = - PublicMethed.getTransactionByIdSolidity(txid, blockingStubSolidity); - Assert.assertEquals(transaction, transactionFromSolidity); - } - - @Test(enabled = true, description = "create sellOrder with value excption") - void marketSellAssetTest002() { - - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey.getAddress(); - String testKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - long sendCoinValue = 10000_000000L; - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress, sendCoinValue, foundationAddress001, foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - Return resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress, - testKey, - assetAccountId001, - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : SellToken balance is not enough !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress, - testKey, - assetAccountId001, - 0, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : token quantity must greater than zero"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - Account account = PublicMethed.queryAccount(testAddress, blockingStubFull); - Assert.assertEquals(account.getBalance(), sendCoinValue); - } - - @Test(enabled = true, description = "create sellOrder with tokenId excption") - void marketSellAssetTest003() { - - long beforeBalance = PublicMethed.queryAccount(testAddress001, blockingStubFull).getBalance(); - logger.info("BeforeBalance: " + beforeBalance); - - Return resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - "xxxx".getBytes(), - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : sellTokenId is not a valid number"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - "xxx".getBytes(), - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : buyTokenId is not a valid number"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - "10001039999".getBytes(), - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : No sellTokenId !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - "10001039999".getBytes(), - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : No buyTokenId !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - assetAccountId001, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : cannot exchange same tokens"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - long afterBalance = PublicMethed.queryAccount(testAddress002, blockingStubFull).getBalance(); - logger.info("AfterBalance: " + afterBalance); - - Assert.assertEquals(beforeBalance, afterBalance); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java deleted file mode 100644 index d145a540f20..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java +++ /dev/null @@ -1,374 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Map; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MarketSellAsset002 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = - PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetIssuedID() - .toByteArray(); - - assetAccountId002 = - PublicMethed.queryAccount(testAddress002, blockingStubFull).getAssetIssuedID() - .toByteArray(); - } - - - @Test(enabled = true, description = "create sellOrder and Match Order") - void marketSellAssetTest001() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - Map beforeAsset002 = PublicMethed - .queryAccount(testAddress002, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed - .marketSellAsset(testAddress001, testKey001, assetAccountId001, sellTokenQuantity, - assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((buyTokenQuantity), afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(sellTokenQuantity, afterAsset002.get(assetId001).longValue()); - - - } - - @Test(enabled = true, description = "create sellOrder and Match Order twice") - void marketSellAssetTest002() { - Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map beforeAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity * 2, - assetAccountId002, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - logger.info("beforeAsset001 :" - + PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetV2Map()); - logger.info("beforeAsset002 :" - + PublicMethed.queryAccount(testAddress002, blockingStubFull).getAssetV2Map()); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId; - orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - // get order Message and RemainSellTokenQuantity - MarketOrder order001 = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - Assert.assertEquals(order001.getSellTokenQuantityRemain(), sellTokenQuantity); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002) + buyTokenQuantity), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001) + sellTokenQuantity, - afterAsset002.get(assetId001).longValue()); - - - String txid3 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid3); - - transaction = PublicMethed - .getTransactionById(txid3, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - // get order Message and RemainSellTokenQuantity - order001 = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - Assert.assertEquals(order001.getSellTokenQuantityRemain(), 0); - - afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002) + buyTokenQuantity * 2), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity * 2, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001) + sellTokenQuantity * 2, - afterAsset002.get(assetId001).longValue()); - - - - } - - @Test(enabled = true, description = "create sellOrder and not Match Order") - void marketSellAssetTest003() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - Map beforeAsset002 = PublicMethed - .queryAccount(testAddress002, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed - .marketSellAsset(testAddress001, testKey001, assetAccountId001, sellTokenQuantity, - assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity * 2, assetAccountId001, sellTokenQuantity * 5, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002).longValue()), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity * 2, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001).longValue(), - afterAsset002.get(assetId001).longValue()); - } - - @Test(enabled = true, description = "CancelOrder") - void marketSellAssetTest004() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - Long sellTokenQuantity001; - byte[] tokenId; - byte[] orderId001; - - orderId001 = orderList.get().getOrders(0).getOrderId().toByteArray(); - tokenId = orderList.get().getOrders(0).getSellTokenId().toByteArray(); - sellTokenQuantity001 = orderList.get().getOrders(0).getSellTokenQuantityRemain(); - - String txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - - String assetId001 = ByteArray.toStr(tokenId); - - Assert.assertEquals(beforeAsset001.get(assetId001) + sellTokenQuantity001, - afterAsset001.get(assetId001).longValue()); - - Return response = PublicMethed - .marketCancelOrderGetResposne(testAddress001, testKey001, orderId001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(response); - Assert.assertEquals(response.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ByteArray.toStr(response.getMessage().toByteArray()).toLowerCase(), - "contract validate error : Order is not active!".toLowerCase()); - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java deleted file mode 100644 index fb7e2898dd2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, - 1, 1, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, - 1, 1, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true, description = "CancelOrder") - void marketCancelAssetTest001() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, 100, - trx, 50, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() == 0); - - } - - @Test(enabled = true, description = "Cancel a cancelled order ") - void marketCancelAssetTest002() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, 100, - trx, 50, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() == 0); - - Assert.assertEquals(PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, - blockingStubFull).toLowerCase(), - "contract validate error : Order is not active!".toLowerCase()); - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java deleted file mode 100644 index 2a911540df4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java +++ /dev/null @@ -1,113 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset004 { - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,20000_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,20000_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey001,blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress002,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey002,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true,description = "The order amount exceeds the balance") - void marketCancelAssetTest002() { - - String txid = PublicMethed.marketSellAsset(testAddress001,testKey001,assetAccountId001,100, - trx,50,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001,testKey001,orderId,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java deleted file mode 100644 index 951c404c6f0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java +++ /dev/null @@ -1,160 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Map; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset005 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - ByteString assetAccountId; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2024_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,2024_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey001,blockingStubFull)); - - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId = PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - - } - - - @Test(enabled = true,description = "Create an order to sell Trx and buy Trc10") - void test01SellTrxBuyTrc10() { - long balanceAfter = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - PublicMethed.transferAsset(testAddress002, assetAccountId001, 10000, testAddress001, - testKey001, blockingStubFull); - final Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, - blockingStubFull).getAssetV2Map(); - - String txid = PublicMethed.marketSellAsset(testAddress002,testKey002,trx, - sellTokenQuantity,assetAccountId001, - buyTokenQuantity,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - logger.info("beforeAsset001: " + beforeAsset001); - - txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity * 2, - trx, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - - String assetId001 = ByteArray.toStr(assetAccountId001); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - - } - - @Test(enabled = true,description = "Create an order to sell Trc10 and buy Trx") - void test02SellTrc10BuyTrx() { - long balanceAfter = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - - final Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, - blockingStubFull).getAssetV2Map(); - - String txid = PublicMethed.marketSellAsset(testAddress002,testKey002,assetAccountId001, - sellTokenQuantity,trx, - buyTokenQuantity,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - logger.info("beforeAsset001: " + beforeAsset001); - - txid = PublicMethed.marketSellAsset(testAddress001, testKey001, trx, - sellTokenQuantity * 2, - assetAccountId001, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - - - } - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java deleted file mode 100644 index 830795dfded..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java +++ /dev/null @@ -1,288 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - - -public class MarketSellAsset006 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - - private ManagedChannel channelSolidity = null; - - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - public ManagedChannel channelPbft = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true, description = "create sellOrder") - void marketSellAssetTest001() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity, assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - } - - @Test(enabled = false, description = "getMarketPairList from solidity and pbft") - void marketSellAssetTest002() { - Optional pairList = PublicMethed - .getMarketPairList(blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional pairList2 = PublicMethed - .getMarketPairListSolidity(blockingStubSolidity); - - - Optional pairList3 = PublicMethed - .getMarketPairListSolidity(blockingStubPbft); - - Assert.assertEquals(pairList,pairList2); - Assert.assertEquals(pairList,pairList3); - - - - } - - @Test(enabled = true, description = "getMarketOrderListByPair from solidity and pbft") - void marketSellAssetTest003() { - Optional orderList = PublicMethed - .getMarketOrderListByPair(assetAccountId001,assetAccountId002,blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubSolidity); - - - Optional orderList3 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubPbft); - - System.out.println(orderList3); - - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - - @Test(enabled = true, description = "GetMarketOrderById from solidity and pbft") - void marketSellAssetTest004() { - Optional orderList = PublicMethed - .getMarketOrderListByPair(assetAccountId001,assetAccountId002,blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubSolidity); - - - Optional orderList3 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubPbft); - - System.out.println(orderList3); - - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - - @Test(enabled = true, description = "GetMarketOrderByAccount from solidity and pbft") - void marketSellAssetTest005() { - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderByAccountSolidity(testAddress001, blockingStubSolidity); - Assert.assertTrue(orderList2.get().getOrdersCount() > 0); - - - Optional orderList3 = PublicMethed - .getMarketOrderByAccountSolidity(testAddress001, blockingStubPbft); - Assert.assertTrue(orderList3.get().getOrdersCount() > 0); - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - @Test(enabled = true, description = "GetMarketOrderById from solidity and pbft") - void marketSellAssetTest006() { - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - MarketOrder order2 = PublicMethed - .getMarketOrderByIdSolidity(orderId, blockingStubSolidity).get(); - - Assert.assertEquals(order2.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order2.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order2.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order2.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order2.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order2.getBuyTokenQuantity(), buyTokenQuantity); - - MarketOrder order3 = PublicMethed - .getMarketOrderByIdSolidity(orderId, blockingStubPbft).get(); - - Assert.assertEquals(order3.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order3.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order3.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order3.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order3.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order3.getBuyTokenQuantity(), buyTokenQuantity); - - - } - - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java deleted file mode 100644 index 124a8d4405f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java +++ /dev/null @@ -1,117 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class EventLog2 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/eventLog2.sol"; - String contractName = "Event"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "test opcode log2") - public void test01EmitLog2() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "messageI()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String logStr1 = ByteArray.toHexString(transactionExtention.getLogs(0).getData().toByteArray()); - Assert.assertTrue(logStr1.contains("000000000000000000000000000000000000000" - + "000000000000000000000000100000000000000000" - + "000000000000000000000000000000000000000000000010000000000000000" - + "000000000000000000000000000000000000000000000001")); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java deleted file mode 100644 index 79075b8dccd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java +++ /dev/null @@ -1,152 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Event query for block") - public void test01EventQueryForBlock() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("blockTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String blockMessage = ""; - - Integer retryTimes = 20; - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (message != null) { - //System.out.println("receive : " + new String(message)); - blockMessage = new String(message); - if (!blockMessage.equals("blockTrigger") && !blockMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("block message:" + blockMessage); - JSONObject blockObject = JSONObject.parseObject(blockMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "blockTrigger"); - Assert.assertTrue(blockObject.getLong("blockNumber") > 0); - Assert.assertTrue(blockObject.containsKey("blockHash")); - Assert.assertTrue(blockObject.getInteger("transactionSize") >= 0); - } - - - @Test(enabled = true, description = "Event query for block on solidity") - public void test02EventQueryForBlockOnSolidity() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String blockMessage = ""; - - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (message != null) { - System.out.println("receive : " + new String(message)); - blockMessage = new String(message); - if (!blockMessage.equals("solidityTrigger") && !blockMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("block message:" + blockMessage); - JSONObject blockObject = JSONObject.parseObject(blockMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityTrigger"); - Assert.assertTrue(blockObject.getLong("latestSolidifiedBlockNumber") > 0); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java deleted file mode 100644 index 8eed6a93ae5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress; - String txid; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for transaction") - public void test01EventQueryForTransaction() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("transactionTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("transactionTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "transactionTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java deleted file mode 100644 index 20cb549cf1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress; - String txid; - - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for contract event") - public void test01EventQueryForContractEvent() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("contractEventTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("contractEventTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "contractEventTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - @Test(enabled = true, description = "Event query for solidity contract event") - public void test02EventQueryForContractSolidityEvent() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityEventTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 40; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - - transactionMessage = new String(message); - logger.info("transaction message:" + transactionMessage); - if (!transactionMessage.equals("solidityEventTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityEventTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java deleted file mode 100644 index f4181489708..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java +++ /dev/null @@ -1,223 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - byte[] contractAddress; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for contract log") - public void test01EventQueryForContractLog() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("contractLogTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("contractLogTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "contractLogTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - @Test(enabled = true, description = "Event query for solidity contract log") - public void test02EventQueryForContractSolidityLog() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityLogTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 40; - String txid1 = ""; - String txid2 = ""; - String txid3 = ""; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid1 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - txid2 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - txid3 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - - } - - if (message != null) { - - transactionMessage = new String(message); - logger.info("transaction message:" + transactionMessage); - if (!transactionMessage.equals("solidityLogTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityLogTrigger"); - txid = blockObject.getString("transactionId"); - - Assert.assertTrue(txid1.equals(txid) || txid2.equals(txid) || txid3.equals(txid)); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java deleted file mode 100644 index 2ca3c357777..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java +++ /dev/null @@ -1,566 +0,0 @@ -package stest.tron.wallet.dailybuild.exceptionfee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AssertException { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger contract Divide 0") - public void test1DivideInt() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "4" + "," + "0"; - - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional ById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + ById.get().getRet(0)); - logger.info("getNumber:" + ById.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + ById.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + ById.get().getRet(0).getContractRet()); - - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - contractResult.REVERT.getNumber()); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), 2); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000012"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract index out of bounds") - public void test2FindArgsContractMinTest() { - String filePath = - "src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol"; - String contractName = "findArgsIContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("11:" + Base58.encode58Check(contractAddress)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "findArgsByIndex1(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract Bytes array index out of bounds") - public void test3ByteMinContract() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol"; - String contractName = "byteContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "testBytesGet(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract convert too large value to enumerated type") - public void test4Enum() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest4Enum.sol"; - String contractName = "enumContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = 22; - - txid = PublicMethed.triggerContract(contractAddress, - "setGoStraight(uint8)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = false, description = "Trigger contract move a negative value to a binary") - public void test5MoveRight() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol"; - String contractName = "binaryRightContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "binaryMoveR(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + maxFeeLimit + netFee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract Call an uninitialized " - + "internal function type variable") - public void test6UninitializedContract() { - String filePath = - "src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol"; - String contractName = "uni"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract assert exception") - public void test7TestAssertContract() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testAssert()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java deleted file mode 100644 index 63a9e642d23..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpRateLimite001 { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - private String httpSoliditynode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(3); - private String realHttpSoliditynode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(4); - - - - /** constructor. */ - @BeforeClass - public void beforeClass() {} - - /** constructor. */ - @Test(enabled = true, description = "Rate limit QpsStrategy for ListWitness interface") - public void test1QpsStrategyForListWitnessInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.listwitnesses(httpnode); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListNodes interface") - public void test2IpQpsStrategyForListNodesInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.listNodes(httpnode); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test( - enabled = true, - description = - "Rate limit IpQpsStrategy for GetBlockByLatestNumOnSolidity " - + "interface on fullnode's solidity service") - public void test3IpQpsStrategyForGetBlockByLatestNumOnSolidityInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 5); - HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 5); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test( - enabled = true, - description = - "Rate limit QpsStrategy for getBlockByNum " + "interface on fullnode's solidity service") - public void test4QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 5); - HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 5); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - @Test( - enabled = false, - description = - "Rate limit QpsStrategy for " - + "getTransactionsFromThisFromSolidity " - + "interface on real solidity") - public void test6QpsStrategyForgetTransactionsToThisFromSolidity() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - logger.info(realHttpSoliditynode); - HttpMethed.getTransactionsToThisFromSolidity(realHttpSoliditynode, fromAddress, 0, 50); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - @Test(enabled = true, description = "Verify getstatsinfo Interface has been disabled") - public void test7GetStatsInfo() { - response = HttpMethed.getStatsInfo(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForGetstatsinfo = responseContent.getString("Error"); - logger.info("resultForGetstatsinfo:" + resultForGetstatsinfo); - Assert.assertEquals(resultForGetstatsinfo, "this API is unavailable due to config"); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException {} -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java deleted file mode 100644 index 12870a5ae5c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java +++ /dev/null @@ -1,107 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by http") - public void getAccount() { - response = HttpMethed.getAccount(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account from solidity by http") - public void getAccountFromSolidity() { - response = HttpMethed.getAccountFromSolidity(httpSoliditynode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account from PBFT by http") - public void getAccountFromPbftNode() { - response = HttpMethed.getAccountFromPbft(httpPbftNode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get accountNet by http") - public void getAccountNet() { - response = HttpMethed.getAccountNet(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(Integer.parseInt(responseContent.get("freeNetLimit").toString()), 5000); - Assert.assertEquals(Long.parseLong(responseContent.get("TotalNetLimit").toString()), - 43200000000L); - Assert.assertTrue(responseContent.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get accountResource by http") - public void getAccountResource() { - response = HttpMethed.getAccountReource(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - Long.parseLong(responseContent.get("TotalEnergyLimit").toString()) >= 50000000000L); - Assert.assertTrue(responseContent.size() >= 3); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java deleted file mode 100644 index d1d8f587580..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java +++ /dev/null @@ -1,335 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeBalanceAddress = ecKey1.getAddress(); - String freezeBalanceKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverResourceAddress = ecKey2.getAddress(); - String receiverResourceKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long berforeBalance; - Long afterBalance; - Long amount = 10000000L; - Long frozenBalance = 2000000L; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance for bandwidth by http") - public void test001FreezebalanceForBandwidth() { - PublicMethed.printAddress(freezeBalanceKey); - //Send trx to test account - response = HttpMethed.sendCoin(httpnode, fromAddress, freezeBalanceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 0, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for bandwidth by http") - public void test002UnFreezebalanceForBandwidth() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance for bandwidth - response = HttpMethed.unFreezeBalance(httpnode, freezeBalanceAddress, 0, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance for energy by http") - public void test003FreezebalanceForEnergy() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance for energy - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 1, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for energy by http") - public void test004UnFreezebalanceForEnergy() { - - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - HttpMethed.waitToProduceOneBlock(httpnode); - //UnFreeze balance for energy - response = HttpMethed.unFreezeBalance(httpnode, freezeBalanceAddress, 1, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance with bandwidth for others by http") - public void test005FreezebalanceOfBandwidthForOthers() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, receiverResourceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance with bandwidth for others - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 0, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource by http") - public void test006GetDelegatedResource() { - response = HttpMethed - .getDelegatedResource(httpnode, freezeBalanceAddress, receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource from solidity by http") - public void test007GetDelegatedResourceFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getDelegatedResourceFromSolidity(httpSoliditynode, freezeBalanceAddress, - receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource from PBFT by http") - public void test008GetDelegatedResourceFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed - .getDelegatedResourceFromPbft(httpPbftNode, freezeBalanceAddress, receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index by http") - public void test009GetDelegatedResourceAccountIndex() { - response = HttpMethed.getDelegatedResourceAccountIndex(httpnode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index from solidity by http") - public void test010GetDelegatedResourceAccountIndexFromSolidity() { - response = HttpMethed - .getDelegatedResourceAccountIndexFromSolidity(httpSoliditynode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index from PBFT by http") - public void test011GetDelegatedResourceAccountIndexFromPbft() { - response = HttpMethed - .getDelegatedResourceAccountIndexFromPbft(httpPbftNode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance with bandwidth for others by http") - public void test012UnFreezebalanceOfBandwidthForOthers() { - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with bandwidth for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 0, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance with energy for others by http") - public void test013FreezebalanceOfEnergyForOthers() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, receiverResourceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance with energy for others - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 1, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance with energy for others by http") - public void test014UnFreezebalanceOfEnergyForOthers() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with energy for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 1, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBlance for tron power by http") - public void test015FreezeTronPower() { - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 2, null, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for tron power by http") - public void test016UnFreezeBalanceForTronPower() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with energy for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 2, null, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, freezeBalanceAddress, fromAddress, freezeBalanceKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java deleted file mode 100644 index a63d3e7f6c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java +++ /dev/null @@ -1,230 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount003 { - - private static String updateAccountName = - "updateAccount_" + System.currentTimeMillis(); - private static String updateUrl = - "http://www.update.url" + System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness1Address = PublicMethed.getFinalAddress(witnessKey001); - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness2Address = PublicMethed.getFinalAddress(witnessKey002); - private final Long createWitnessAmount = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.createWitnessAmount"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey1.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] updateAccountAddress = ecKey2.getAddress(); - String updateAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 50000000L; - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Update account by http") - public void test01UpdateAccount() { - response = HttpMethed.sendCoin(httpnode, fromAddress, updateAccountAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed - .updateAccount(httpnode, updateAccountAddress, updateAccountName, updateAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, updateAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getString("account_name") - .equalsIgnoreCase(HttpMethed.str2hex(updateAccountName))); - - Assert.assertFalse(responseContent.getString("active_permission").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Vote witness account by http") - public void test02VoteWitnessAccount() { - //Freeze balance - response = HttpMethed - .freezeBalance(httpnode, updateAccountAddress, 40000000L, 0, 2, updateAccountKey); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - voteElement.addProperty("vote_address", ByteArray.toHexString(witness1Address)); - voteElement.addProperty("vote_count", 11); - voteKeys.add(voteElement); - - voteElement.remove("vote_address"); - voteElement.remove("vote_count"); - voteElement.addProperty("vote_address", ByteArray.toHexString(witness2Address)); - voteElement.addProperty("vote_count", 12); - voteKeys.add(voteElement); - - response = HttpMethed - .voteWitnessAccount(httpnode, updateAccountAddress, voteKeys, updateAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, updateAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("votes").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses by http") - public void test03ListWitness() { - response = HttpMethed.listwitnesses(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses from solidity by http") - public void test04ListWitnessFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listwitnessesFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses from PBFT by http") - public void test05ListWitnessFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listwitnessesFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Update witness by http") - public void test06UpdateWitness() { - response = HttpMethed.updateWitness(httpnode, witness1Address, updateUrl, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.listwitnesses(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getString("witnesses").indexOf(updateUrl) != -1); - //logger.info("result is " + responseContent.getString("witnesses").indexOf(updateUrl)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Create account by http") - public void test07CreateAccount() { - PublicMethed.printAddress(newAccountKey); - response = HttpMethed.createAccount(httpnode, fromAddress, newAccountAddress, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, newAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getLong("create_time") > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Create witness by http") - public void test08CreateWitness() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, newAccountAddress, createWitnessAmount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - PublicMethed.printAddress(newAccountKey); - - response = HttpMethed.createWitness(httpnode, newAccountAddress, updateUrl); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("txID").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Withdraw by http") - public void test09Withdraw() { - response = HttpMethed.withdrawBalance(httpnode, witness1Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert - .assertTrue(responseContent.getString("Error").indexOf("is a guard representative") != -1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Unfreeze balance for tron power by http") - public void test10UnfreezeTronPower() { - response = HttpMethed.unFreezeBalance(httpnode, updateAccountAddress,2,updateAccountKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, updateAccountAddress, fromAddress, updateAccountKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java deleted file mode 100644 index 5ae5089d057..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java +++ /dev/null @@ -1,115 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] setAccountIdAddress = ecKey1.getAddress(); - String setAccountIdKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 10000000L; - String accountId; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - - - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Set account by http") - public void test1setAccountId() { - response = HttpMethed.sendCoin(httpnode, fromAddress, setAccountIdAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed - .setAccountId(httpnode, setAccountIdAddress, System.currentTimeMillis() + "id", false, - setAccountIdKey); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //Set account id. - accountId = System.currentTimeMillis() + "id"; - response = HttpMethed - .setAccountId(httpnode, setAccountIdAddress, accountId, true, setAccountIdKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via http") - public void test2getAccountId() { - response = HttpMethed.getAccountById(httpnode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - - response = HttpMethed.getAccountById(httpnode, accountId, false); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() <= 1); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via http") - public void test3getAccountIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAccountByIdFromSolidity(httpSoliditynode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via PBFT http") - public void test4getAccountIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAccountByIdFromPbft(httpPbftNode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, setAccountIdAddress, fromAddress, setAccountIdKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java deleted file mode 100644 index 4d45d5e8b0e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java +++ /dev/null @@ -1,62 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] toAddress = ecKey1.getAddress(); - String toAddressKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 1L; - String sendText = "Decentralize the WEB!"; - private JSONObject responseContent; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, description = "Test transfer with notes by http") - public void test01TransferWithNotes() { - PublicMethed.printAddress(toAddressKey); - //Send trx to test account - String txid = HttpMethed - .sendCoin(httpnode, fromAddress, toAddress, amount, sendText, testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpResponse response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String rawData = responseContent.getString("raw_data"); - JSONObject rawDataObject = JSON.parseObject(rawData); - Assert.assertTrue(rawDataObject.containsKey("data")); - String hexData = rawDataObject.getString("data"); - String recoveredString = new String(ByteUtil.hexToBytes(hexData)); - Assert.assertEquals(sendText, recoveredString); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, toAddress, fromAddress, toAddressKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java deleted file mode 100644 index f57780e5bc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java +++ /dev/null @@ -1,311 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAsset001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String updateDescription = "Description_update_" + now; - private static String updateUrl = "Url_update_" + now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] assetAddress = ecKey1.getAddress(); - String assetKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey2.getAddress(); - String participateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getAssetIssueByIdContent; - private JSONObject getAssetIssueByNameContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Create asset issue by http") - public void test01CreateAssetIssue() { - response = HttpMethed.sendCoin(httpnode, fromAddress, assetAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .sendCoin(httpnode, fromAddress, participateAddress, 10000000L, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, assetAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, assetAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - assetIssueId = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId); - Assert.assertTrue(Integer.parseInt(assetIssueId) > 1000000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById by http") - public void test02GetAssetIssueById() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAssetIssueById(httpnode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById from solidity by http") - public void test03GetAssetIssueByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueByIdFromSolidity(httpSoliditynode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById from PBFT by http") - public void test04GetAssetIssueByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueByIdFromPbft(httpPbftNode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName by http") - public void test05GetAssetIssueByName() { - response = HttpMethed.getAssetIssueByName(httpnode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName from solidity by http") - public void test06GetAssetIssueByNameFromSolidity() { - response = HttpMethed.getAssetIssueByNameFromSolidity(httpSoliditynode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName from PBFT by http") - public void test07GetAssetIssueByNameFromPbft() { - response = HttpMethed.getAssetIssueByNameFromPbft(httpPbftNode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "TransferAsset by http") - public void test08TransferAsset() { - logger.info("Transfer asset."); - response = HttpMethed - .transferAsset(httpnode, assetAddress, participateAddress, assetIssueId, 100L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, participateAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("assetV2").isEmpty()); - //logger.info(responseContent.get("assetV2").toString()); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Participate asset issue by http") - public void test09ParticipateAssetIssue() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .participateAssetIssue(httpnode, assetAddress, participateAddress, assetIssueId, 1000L, - participateKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, participateAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Update asset issue by http") - public void test10UpdateAssetIssue() { - response = HttpMethed - .updateAssetIssue(httpnode, assetAddress, updateDescription, updateUrl, 290L, 390L, - assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAssetIssueById(httpnode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - - Assert.assertTrue(getAssetIssueByIdContent.getLong("public_free_asset_net_limit") == 390L); - Assert.assertTrue(getAssetIssueByIdContent.getLong("free_asset_net_limit") == 290L); - Assert.assertTrue(getAssetIssueByIdContent.getString("description") - .equalsIgnoreCase(HttpMethed.str2hex(updateDescription))); - Assert.assertTrue( - getAssetIssueByIdContent.getString("url").equalsIgnoreCase(HttpMethed.str2hex(updateUrl))); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list by http") - public void test11GetAssetissueList() { - - response = HttpMethed.getAssetissueList(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list from solidity by http") - public void test12GetAssetissueListFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list from PBFT by http") - public void test13GetAssetissueListFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list by http") - public void test14GetPaginatedAssetissueList() { - response = HttpMethed.getPaginatedAssetissueList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list from solidity by http") - public void test15GetPaginatedAssetissueListFromSolidity() { - response = HttpMethed.getPaginatedAssetissueListFromSolidity(httpSoliditynode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list from PBFT by http") - public void test16GetPaginatedAssetissueListFromPbft() { - response = HttpMethed.getPaginatedAssetissueListFromPbft(httpPbftNode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetAddress, fromAddress, assetKey); - HttpMethed.freedResource(httpnode, participateAddress, fromAddress, participateKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java deleted file mode 100644 index f091e8f4b05..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java +++ /dev/null @@ -1,383 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestBlock001 { - - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private Integer currentBlockNum; - private JSONObject blockContent; - private JSONObject blockContentWithVisibleTrue; - private String blockId; - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block by http") - public void get01NowBlock() { - response = HttpMethed.getNowBlock(httpnode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from solidity by http") - public void get02NowBlockFromSolidity() { - response = HttpMethed.getNowBlockFromSolidity(httpSoliditynode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from pbft by http") - public void get03NowBlockFromPbft() { - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num by http") - public void get04BlockByNum() { - response = HttpMethed.getBlockByNum(httpnode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - - //visible=true - response = HttpMethed.getBlockByNum(httpnode, currentBlockNum, true); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent.getString("blockID"), - blockContent.getString("blockID")); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num from solidity by http") - public void get05BlockByNumFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBlockByNumFromSolidity(httpSoliditynode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num from PBFT by http") - public void get06BlockByNumFromPbft() { - response = HttpMethed.getBlockByNumFromPbft(httpPbftNode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by http") - public void get07BlockByLimitNext() { - response = HttpMethed.getBlockByLimitNext(httpnode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by http") - public void get08BlockByLastNum() { - response = HttpMethed.getBlockByLastNum(httpnode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by http") - public void get09BlockById() { - response = HttpMethed.getBlockById(httpnode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by Solidity http") - public void get10BlockByIdFromSolidity() { - response = HttpMethed.getBlockByIdFromSolidity(httpSoliditynode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by PBFT http") - public void get11BlockByIdFromPbft() { - response = HttpMethed.getBlockByIdFromPbft(httpPbftNode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "List nodes by http") - public void get12ListNodes() { - response = HttpMethed.listNodes(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "get next maintenance time by http") - public void get13NextMaintaenanceTime() { - response = HttpMethed.getNextmaintenanceTime(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("num").toString().isEmpty()); - Assert.assertTrue(responseContent.getLong("num") >= System.currentTimeMillis()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "get chain parameter by http") - public void get14ChainParameter() { - response = HttpMethed.getChainParameter(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("chainParameter").toString()); - Assert.assertTrue(jsonArray.size() >= 26); - Boolean exsistDelegated = false; - for (int i = 0; i < jsonArray.size(); i++) { - if (jsonArray.getJSONObject(i).getString("key").equals("getAllowDelegateResource")) { - exsistDelegated = true; - Assert.assertTrue(jsonArray.getJSONObject(i).getString("value").equals("1")); - } - } - Assert.assertTrue(exsistDelegated); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "get Node Info by http") - public void get15NodeInfo() { - response = HttpMethed.getNodeInfo(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("configNodeInfo").toString().isEmpty()); - Assert.assertTrue(responseContent.getString("configNodeInfo").contains("\"dbVersion\":2")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction count by blocknum from solidity by http") - public void get16TransactionCountByBlocknumFromSolidity() { - response = HttpMethed - .getTransactionCountByBlocknumFromSolidity(httpSoliditynode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 1); - Assert.assertTrue(Integer.parseInt(responseContent.get("count").toString()) >= 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction count by blocknum from PBFT by http") - public void get17TransactionCountByBlocknumFromPbft() { - response = HttpMethed.getTransactionCountByBlocknumFromPbft(httpPbftNode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 1); - Assert.assertTrue(Integer.parseInt(responseContent.get("count").toString()) >= 0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by Solidity http") - public void get18BlockByLimitNextFromSolidity() { - response = HttpMethed - .getBlockByLimitNextFromSolidity(httpSoliditynode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by PBFT http") - public void get19BlockByLimitNextFromPbft() { - response = HttpMethed - .getBlockByLimitNextFromPbft(httpPbftNode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by solidity http") - public void get20BlockByLastNumFromSolidity() { - response = HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by PBFT http") - public void get21BlockByLastNumFromPbft() { - response = HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Get block by num by http") - public void get16TestResponse() { - Integer times = 1000; - String testKey002 = "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25"; - byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Long duration = HttpMethed.getBlockByNumForResponse(httpnode, 4942435, times); - /* Long duration = HttpMethed.getAccountForResponse(httpnode, fromAddress, times);*/ - /* Long duration = HttpMethed.getTransactionByIdForResponse(httpnode, - "a265fc457551fd9cfa55daec0550268b1a2da54018cc700f1559454836de411c", times);*/ - logger.info("Total duration : " + duration); - logger.info("Average duration: " + duration / times); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java deleted file mode 100644 index 41040cc8e97..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java +++ /dev/null @@ -1,185 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import static org.hamcrest.core.StringContains.containsString; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestClearAbiContract001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String contractAddress; - String abi; - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy smart contract by http") - public void test1DeployContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, assetOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - logger.info("abi:" + abi); - logger.info("code:" + code); - - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test2GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertThat(responseContent.getString("abi"), containsString("testView")); - - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test3TriggerConstantContract() { - - HttpResponse httpResponse = HttpMethed - .triggerConstantContract(httpnode, assetOwnerAddress, contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - httpResponse = HttpMethed.triggerConstantContractFromSolidity(httpSoliditynode, - assetOwnerAddress, contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - - httpResponse = HttpMethed.triggerConstantContractFromPbft(httpPbftnode, assetOwnerAddress, - contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test4ClearAbiContract() { - - HttpResponse httpResponse = HttpMethed - .clearABiGetTxid(httpnode, assetOwnerAddress, contractAddress, assetOwnerKey); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "true"); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test5GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("abi"), "{}"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java deleted file mode 100644 index 811a0b44cc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java +++ /dev/null @@ -1,119 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestConstantContract001 { - - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String contractAddress; - Long amount = 2048000000L; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy constant contract by http") - public void test1DeployConstantContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - String filePath = "src/test/resources/soliditycode/constantContract001.sol"; - contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get constant contract by http") - public void test2GetConstantContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger constant contract without parameterString by http") - public void test3TriggerConstantContract() { - String param1 = - "000000000000000000000000000000000000000000000000000000000000000" + Integer.toHexString(3); - String param2 = - "00000000000000000000000000000000000000000000000000000000000000" + Integer.toHexString(30); - logger.info(param1); - logger.info(param2); - String param = param1 + param2; - logger.info(ByteArray.toHexString(assetOwnerAddress)); - response = HttpMethed.triggerConstantContract(httpnode, assetOwnerAddress, contractAddress, - "testPure(uint256,uint256)", param, 1000000000L, assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("transaction").isEmpty()); - JSONObject transactionObject = HttpMethed - .parseStringContent(responseContent.getString("transaction")); - Assert.assertTrue(!transactionObject.getString("raw_data").isEmpty()); - Assert.assertTrue(!transactionObject.getString("raw_data_hex").isEmpty()); - Assert.assertTrue(responseContent.getIntValue("energy_used") > 400 - && responseContent.getIntValue("energy_used") < 500); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java deleted file mode 100644 index 7d38b0540c6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java +++ /dev/null @@ -1,314 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestExchange001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private static Integer exchangeId; - private static Long beforeInjectBalance; - private static Long afterInjectBalance; - private static Long beforeWithdrawBalance; - private static Long afterWithdrawBalance; - private static Long beforeTransactionBalance; - private static Long afterTransactionBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeOwnerAddress = ecKey1.getAddress(); - String exchangeOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset2Address = ecKey2.getAddress(); - String asset2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Create asset issue by http") - public void test01CreateExchange() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, exchangeOwnerAddress, 2048000000L, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, exchangeOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.assetIssue(httpnode, asset2Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, exchangeOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.getAccount(httpnode, asset2Address); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - response = HttpMethed - .transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, 10000000000L, - asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create exchange. - response = HttpMethed - .exchangeCreate(httpnode, exchangeOwnerAddress, assetIssueId1, 1000000L, assetIssueId2, - 1000000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges by http") - public void test02ListExchange() { - response = HttpMethed.listExchanges(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges from solidity by http") - public void test03ListExchangeFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listExchangesFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges from PBFT by http") - public void test04ListExchangeFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listExchangesFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById by http") - public void test05GetExchangeById() { - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById from solidity by http") - public void test06GetExchangeByIdFromSolidity() { - response = HttpMethed.getExchangeByIdFromSolidity(httpSoliditynode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById from Pbft by http") - public void test07GetExchangeByIdFromPbft() { - response = HttpMethed.getExchangeByIdFromPbft(httpPbftNode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Inject exchange by http") - public void test08InjectExchange() { - //Inject exchange. - response = HttpMethed - .exchangeInject(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 300L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterInjectBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info("afterInjectBalance" + afterInjectBalance); - Assert.assertTrue(afterInjectBalance - beforeInjectBalance == 300L); - beforeWithdrawBalance = afterInjectBalance; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Withdraw exchange by http") - public void test09WithdrawExchange() { - //Withdraw exchange. - response = HttpMethed - .exchangeWithdraw(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 170L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterWithdrawBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(beforeWithdrawBalance - afterWithdrawBalance == 170L); - beforeTransactionBalance = afterWithdrawBalance; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Transaction exchange by http") - public void test10TransactionExchange() { - //Transaction exchange. - response = HttpMethed - .exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 100L, 1L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterTransactionBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(afterTransactionBalance - beforeTransactionBalance >= 1); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get asset issue list by name by http") - public void test11GetAssetIssueListByName() { - response = HttpMethed.getAssetIssueListByName(httpnode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get asset issue list by name from solidity and pbft by http") - public void test12GetAssetIssueListByNameFromSolidityAndPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListByNameFromSolidity(httpSoliditynode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - - response = HttpMethed.getAssetIssueListByNameFromPbft(httpPbftNode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated exchange list by http") - public void test13GetPaginatedExchangeList() { - - response = HttpMethed.getPaginatedExchangeList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, asset2Address, fromAddress, asset2Key); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java deleted file mode 100644 index 4ce34f4cefe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestGetAccountBalance001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] randomAddress = ecKey3.getAddress(); - Long amount = 2048000000L; - String txid; - Integer sendcoinBlockNumber; - String sendcoinBlockHash; - Integer deployContractBlockNumber; - String deployContractBlockHash; - Long fee; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Deploy smart contract by http") - public void test01DeployContractForTest() { - HttpMethed.waitToProduceOneBlock(httpnode); - PublicMethed.printAddress(assetOwnerKey); - txid = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, "", testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - txid = HttpMethed.sendCoin(httpnode, assetOwnerAddress, randomAddress, - amount / 1000000L, "", assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sendcoinBlockNumber = responseContent.getInteger("blockNumber"); - Assert.assertTrue(sendcoinBlockNumber > 0); - - response = HttpMethed.getBlockByNum(httpnode, sendcoinBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sendcoinBlockHash = responseContent.getString("blockID"); - - String contractName = "transferTokenContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractTrcToken001_transferTokenContract"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractTrcToken001_transferTokenContract"); - txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - fee = responseContent.getLong("fee"); - deployContractBlockNumber = responseContent.getInteger("blockNumber"); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - - response = HttpMethed.getBlockByNum(httpnode, deployContractBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - deployContractBlockHash = responseContent.getString("blockID"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account balance by http") - public void test01GetAccountBalance() { - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - sendcoinBlockNumber, sendcoinBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - final Long beforeBalance = responseContent.getLong("balance"); - - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - Long afterBalance = responseContent.getLong("balance"); - - Assert.assertTrue(beforeBalance - afterBalance == fee); - - - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - - - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block balance by http") - public void test02GetBlockBalance() { - response = HttpMethed.getBlockBalance(httpnode, - sendcoinBlockNumber, sendcoinBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertEquals(sendcoinBlockNumber, responseContent.getJSONObject("block_identifier") - .getInteger("number")); - JSONObject transactionObject = responseContent.getJSONArray("transaction_balance_trace") - .getJSONObject(0); - Assert.assertEquals(transactionObject.getString("type"), "TransferContract"); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(0).getLong("amount")) == 100000L); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(1).getLong("amount")) == amount / 1000000L); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(2).getLong("amount")) == amount / 1000000L); - - response = HttpMethed.getBlockBalance(httpnode, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - - transactionObject = responseContent.getJSONArray("transaction_balance_trace").getJSONObject(0); - Assert.assertEquals(transactionObject.getString("transaction_identifier"), txid); - Assert.assertEquals(transactionObject.getString("type"), "CreateSmartContract"); - Assert.assertTrue(transactionObject.getJSONArray("operation") - .getJSONObject(0).getLong("amount") == -fee); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get burn trx by http") - public void test03GetBurnTrx() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, "", testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - final Long beforeBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey3.getAddress(); - - HttpMethed.sendCoin(httpnode, assetOwnerAddress, receiverAddress, amount - 103000L, - "", assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Long afterBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); - logger.info(afterBurnTrxAmount + " : " + beforeBurnTrxAmount); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000L); - - Assert.assertEquals(afterBurnTrxAmount, HttpMethed.getBurnTrxFromSolidity(httpSolidityNode)); - Assert.assertEquals(afterBurnTrxAmount, HttpMethed.getBurnTrxFromPbft(httpPbftNode)); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get receipt root by http") - public void test04GetReceiptRootByHttp() { - response = HttpMethed.getBlockByNum(httpnode,sendcoinBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String receiptsRoot = responseContent.getJSONObject("block_header").getJSONObject("raw_data") - .getString("receiptsRoot"); - Assert.assertNotEquals(receiptsRoot, - "0000000000000000000000000000000000000000000000000000000000000000"); - Assert.assertFalse(receiptsRoot.isEmpty()); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java deleted file mode 100644 index 8dfe0701288..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java +++ /dev/null @@ -1,533 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMarket001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sellAddress = ecKey1.getAddress(); - String sellKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String txId1; - String txId2; - String orderId; - String orderId1; - String orderId2; - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getMarketOrderByIdContent; - private JSONObject getMarketOrderByIdContentFromSolidity; - private JSONObject getMarketOrderByIdContentFromPbft; - private JSONObject getMarketOrderByAccountContent; - private JSONObject getMarketOrderByAccountContentFromSolidity; - private JSONObject getMarketOrderByAccountContentFromPbft; - private JSONObject getMarketPairListContent; - private JSONObject getMarketPairListContentFromSolidity; - private JSONObject getMarketPairListContentFromPbft; - private JSONObject getMarketOrderListByPairContent; - private JSONObject getMarketOrderListByPairContentFromSolidity; - private JSONObject getMarketOrderListByPairContentFromPbft; - private JSONObject getMarketPriceByPairContent; - private JSONObject getMarketPriceByPairContentFromSolidity; - private JSONObject getMarketPriceByPairContentFromPbft; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketSellAsset trx with trc10 by http") - public void test01MarketSellAsset() { - PublicMethed.printAddress(sellKey); - PublicMethed.printAddress(dev002Key); - - response = HttpMethed.sendCoin(httpnode, fromAddress, sellAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, dev002Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, sellAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, sellKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId1); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.assetIssue(httpnode, dev002Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, dev002Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId2); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - // transferAsset - response = HttpMethed - .transferAsset(httpnode, dev002Address, sellAddress, assetIssueId2, 10000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - // marketsellasset trc10-trc10 - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, assetIssueId2, 500L, - sellKey, "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId = responseContent.getString("orderId"); - logger.info("orderId:" + orderId); - - // marketsellasset trx-trc10 - txId1 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, "_", 1000L, assetIssueId1, 20L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId1); - response = HttpMethed.getTransactionInfoById(httpnode, txId1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId1 = responseContent.getString("orderId"); - logger.info("orderId1:" + orderId1); - - // marketsellasset trc10-trx - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, "_", 500L, sellKey, - "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject orderDetails = responseContent.getJSONArray("orderDetails").getJSONObject(0); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - Assert.assertTrue(500L == orderDetails.getLong("fillBuyQuantity")); - Assert.assertTrue(10L == orderDetails.getLong("fillSellQuantity")); - Assert - .assertEquals(responseContent.getString("orderId"), orderDetails.getString("takerOrderId")); - Assert.assertEquals(orderId1, orderDetails.getString("makerOrderId")); - orderId2 = responseContent.getString("orderId"); - logger.info("orderId2:" + orderId2); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http") - public void test02GetMarketOrderById() { - // getMarketOrderById orderId1 - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderById(httpnode, orderId1, "true"); - getMarketOrderByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContent); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContent.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContent.getString("sell_token_id")); - Assert.assertTrue(1000L == getMarketOrderByIdContent.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, getMarketOrderByIdContent.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContent.getLong("buy_token_quantity")); - Assert.assertTrue(500L == getMarketOrderByIdContent.getLong("sell_token_quantity_remain")); - - // getMarketOrderById orderId2 - HttpResponse response2 = HttpMethed.getMarketOrderById(httpnode, orderId2, "false"); - JSONObject getMarketOrderByIdContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(getMarketOrderByIdContent2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from solidity") - public void test03GetMarketOrderByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getMarketOrderByIdFromSolidity(httpSolidityNode, orderId1, "true"); - getMarketOrderByIdContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromSolidity); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContentFromSolidity.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContentFromSolidity.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, - getMarketOrderByIdContentFromSolidity.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromSolidity.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from pbft") - public void test04GetMarketOrderByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getMarketOrderByIdFromPbft(httpPbftNode, orderId1, "true"); - getMarketOrderByIdContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromPbft); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContentFromPbft.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContentFromPbft.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, - getMarketOrderByIdContentFromPbft.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromPbft.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http") - public void test05GetMarketOrderByAccount() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContent.getJSONArray("orders").getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from solidity") - public void test06GetMarketOrderByAccountFromSolidity() { - response = HttpMethed - .getMarketOrderByAccountFromSolidity(httpSolidityNode, sellAddress, "true"); - getMarketOrderByAccountContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromSolidity.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from pbft") - public void test07GetMarketOrderByAccountFromPbft() { - response = HttpMethed.getMarketOrderByAccountFromPbft(httpPbftNode, sellAddress, "true"); - getMarketOrderByAccountContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromPbft.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http") - public void test08GetMarketPairList() { - response = HttpMethed.getMarketPairList(httpnode, "true"); - getMarketPairListContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContent.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from solidity") - public void test09GetMarketPairListFromSolidity() { - response = HttpMethed.getMarketPairListFromSolidity(httpSolidityNode, "true"); - getMarketPairListContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromSolidity.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from pbft") - public void test10GetMarketPairListFromPbft() { - response = HttpMethed.getMarketPairListFromPbft(httpPbftNode, "true"); - getMarketPairListContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromPbft.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http") - public void test11GetMarketOrderListByPair() { - response = HttpMethed.getMarketOrderListByPair(httpnode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContent.getJSONArray("orders") - .getJSONObject(getMarketOrderListByPairContent.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContent.getLong("sell_token_quantity"), - getMarketOrderListByPairContent.getLong("sell_token_quantity_remain")); - - Assert.assertTrue(getMarketOrderListByPairContent.getJSONArray("orders").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from solidity") - public void test12GetMarketOrderListByPairFromSolidity() { - response = HttpMethed - .getMarketOrderListByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromSolidity.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from pbft") - public void test13GetMarketOrderListByPairFromPbft() { - response = HttpMethed - .getMarketOrderListByPairFromPbft(httpPbftNode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromPbft.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http") - public void test14GetMarketPriceByPair() { - response = HttpMethed.getMarketPriceByPair(httpnode, "_", assetIssueId1, "true"); - getMarketPriceByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContent.getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, getMarketPriceByPairContent.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContent.getJSONArray("prices").getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContent.getJSONArray("prices").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from solidity") - public void test15GetMarketPriceByPairFromSolidity() { - response = HttpMethed - .getMarketPriceByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "true"); - getMarketPriceByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContentFromSolidity.getString("sell_token_id")); - Assert - .assertEquals(assetIssueId1, - getMarketPriceByPairContentFromSolidity.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromSolidity.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromSolidity.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from pbft") - public void test16GetMarketPriceByPairFromPbft() { - response = HttpMethed - .getMarketPriceByPairFromPbft(httpPbftNode, "_", assetIssueId1, "true"); - getMarketPriceByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContentFromPbft.getString("sell_token_id")); - Assert - .assertEquals(assetIssueId1, - getMarketPriceByPairContentFromPbft.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromPbft.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromPbft.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketCancelOrder trx with trc10 by http") - public void test17MarketCancelOrder() { - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(2, getMarketOrderByAccountContent.getJSONArray("orders").size()); - - // MarketCancelOrder - String txId = HttpMethed.marketCancelOrder(httpnode, sellAddress, orderId1, sellKey, "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId); - response = HttpMethed.getTransactionInfoById(httpnode, txId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(1, getMarketOrderByAccountContent.getJSONArray("orders").size()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, sellAddress, fromAddress, sellKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java deleted file mode 100644 index 91217ff06ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java +++ /dev/null @@ -1,534 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMarket002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sellAddress = ecKey1.getAddress(); - String sellKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String txId1; - String txId2; - String orderId; - String orderId1; - String orderId2; - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getMarketOrderByIdContent; - private JSONObject getMarketOrderByIdContentFromSolidity; - private JSONObject getMarketOrderByIdContentFromPbft; - private JSONObject getMarketOrderByAccountContent; - private JSONObject getMarketOrderByAccountContentFromSolidity; - private JSONObject getMarketOrderByAccountContentFromPbft; - private JSONObject getMarketPairListContent; - private JSONObject getMarketPairListContentFromSolidity; - private JSONObject getMarketPairListContentFromPbft; - private JSONObject getMarketOrderListByPairContent; - private JSONObject getMarketOrderListByPairContentFromSolidity; - private JSONObject getMarketOrderListByPairContentFromPbft; - private JSONObject getMarketPriceByPairContent; - private JSONObject getMarketPriceByPairContentFromSolidity; - private JSONObject getMarketPriceByPairContentFromPbft; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketSellAsset trx with trc10 by http") - public void test01MarketSellAsset() { - PublicMethed.printAddress(sellKey); - PublicMethed.printAddress(dev002Key); - - response = HttpMethed.sendCoin(httpnode, fromAddress, sellAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, dev002Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, sellAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, sellKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId1); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.assetIssue(httpnode, dev002Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, dev002Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId2); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - // transferAsset - response = HttpMethed - .transferAsset(httpnode, dev002Address, sellAddress, assetIssueId2, 10000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - // marketsellasset trc10-trc10 - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, assetIssueId2, 500L, - sellKey, "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId = responseContent.getString("orderId"); - logger.info("orderId:" + orderId); - - // marketsellasset trx-trc10 - txId1 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, "_", 1000L, assetIssueId1, 20L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId1); - response = HttpMethed.getTransactionInfoById(httpnode, txId1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId1 = responseContent.getString("orderId"); - logger.info("orderId1:" + orderId1); - - // marketsellasset trc10-trx - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, "_", 500L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject orderDetails = responseContent.getJSONArray("orderDetails").getJSONObject(0); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - Assert.assertTrue(500L == orderDetails.getLong("fillBuyQuantity")); - Assert.assertTrue(10L == orderDetails.getLong("fillSellQuantity")); - Assert - .assertEquals(responseContent.getString("orderId"), orderDetails.getString("takerOrderId")); - Assert.assertEquals(orderId1, orderDetails.getString("makerOrderId")); - orderId2 = responseContent.getString("orderId"); - logger.info("orderId2:" + orderId2); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http") - public void test02GetMarketOrderById() { - // getMarketOrderById orderId1 - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderById(httpnode, orderId1, "false"); - getMarketOrderByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContent); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContent.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContent.getString("sell_token_id")); - Assert.assertTrue(1000L == getMarketOrderByIdContent.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContent.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContent.getLong("buy_token_quantity")); - Assert.assertTrue(500L == getMarketOrderByIdContent.getLong("sell_token_quantity_remain")); - - // getMarketOrderById orderId2 - HttpResponse response2 = HttpMethed.getMarketOrderById(httpnode, orderId2, "false"); - JSONObject getMarketOrderByIdContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(getMarketOrderByIdContent2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from solidity") - public void test03GetMarketOrderByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getMarketOrderByIdFromSolidity(httpSolidityNode, orderId1, "false"); - getMarketOrderByIdContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromSolidity); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContentFromSolidity.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContentFromSolidity.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContentFromSolidity.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromSolidity.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from pbft") - public void test04GetMarketOrderByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getMarketOrderByIdFromPbft(httpPbftNode, orderId1, "false"); - getMarketOrderByIdContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromPbft); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContentFromPbft.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContentFromPbft.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContentFromPbft.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromPbft.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http") - public void test05GetMarketOrderByAccount() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContent.getJSONArray("orders").getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from solidity") - public void test06GetMarketOrderByAccountFromSolidity() { - response = HttpMethed - .getMarketOrderByAccountFromSolidity(httpSolidityNode, sellAddress, "false"); - getMarketOrderByAccountContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromSolidity.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from pbft") - public void test07GetMarketOrderByAccountFromPbft() { - response = HttpMethed.getMarketOrderByAccountFromPbft(httpPbftNode, sellAddress, "false"); - getMarketOrderByAccountContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromPbft.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http") - public void test08GetMarketPairList() { - response = HttpMethed.getMarketPairList(httpnode, "false"); - getMarketPairListContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContent.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from solidity") - public void test09GetMarketPairListFromSolidity() { - response = HttpMethed.getMarketPairListFromSolidity(httpSolidityNode, "false"); - getMarketPairListContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromSolidity.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from pbft") - public void test10GetMarketPairListFromPbft() { - response = HttpMethed.getMarketPairListFromPbft(httpPbftNode, "false"); - getMarketPairListContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromPbft.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http") - public void test11GetMarketOrderListByPair() { - response = HttpMethed.getMarketOrderListByPair(httpnode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContent.getJSONArray("orders") - .getJSONObject(getMarketOrderListByPairContent.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContent.getLong("sell_token_quantity"), - getMarketOrderListByPairContent.getLong("sell_token_quantity_remain")); - - Assert.assertTrue(getMarketOrderListByPairContent.getJSONArray("orders").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from solidity") - public void test12GetMarketOrderListByPairFromSolidity() { - response = HttpMethed - .getMarketOrderListByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromSolidity.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from pbft") - public void test13GetMarketOrderListByPairFromPbft() { - response = HttpMethed - .getMarketOrderListByPairFromPbft(httpPbftNode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromPbft.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http") - public void test14GetMarketPriceByPair() { - response = HttpMethed.getMarketPriceByPair(httpnode, "_", assetIssueId1, "false"); - getMarketPriceByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContent.getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContent.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContent.getJSONArray("prices").getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContent.getJSONArray("prices").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from solidity") - public void test15GetMarketPriceByPairFromSolidity() { - response = HttpMethed - .getMarketPriceByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "false"); - getMarketPriceByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContentFromSolidity.getString("sell_token_id")); - Assert - .assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContentFromSolidity.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromSolidity.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromSolidity.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from pbft") - public void test16GetMarketPriceByPairFromPbft() { - response = HttpMethed - .getMarketPriceByPairFromPbft(httpPbftNode, "_", assetIssueId1, "false"); - getMarketPriceByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContentFromPbft.getString("sell_token_id")); - Assert - .assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContentFromPbft.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromPbft.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromPbft.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketCancelOrder trx with trc10 by http") - public void test17MarketCancelOrder() { - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(2, getMarketOrderByAccountContent.getJSONArray("orders").size()); - - // MarketCancelOrder - String txId = HttpMethed.marketCancelOrder(httpnode, sellAddress, orderId1, sellKey, "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId); - response = HttpMethed.getTransactionInfoById(httpnode, txId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(1, getMarketOrderByAccountContent.getJSONArray("orders").size()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, sellAddress, fromAddress, sellKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java deleted file mode 100644 index d41e49ead51..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.math.BigInteger; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMortgageMechanism01 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - private final String witnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress2 = PublicMethed.getFinalAddress(witnessKey2); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBrokerage by http") - public void test01GetBrokerage() { - response = HttpMethed.getBrokerage(httpnode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - response = HttpMethed.getBrokerageOnVisible(httpnode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - response = HttpMethed.getBrokerageOnVisible(httpnode, fromAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - @Test(enabled = true, description = "GetBrokerage from solidity by http") - public void test02GetBrokerageFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromSolidity(httpSoliditynode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed - .getBrokerageFromSolidityOnVisible(httpSoliditynode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromSolidityOnVisible(httpSoliditynode, fromAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBrokerage from PBFT by http") - public void test03GetBrokerageFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromPbft(httpPbftNode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateBrokerage by http") - public void test04UpdateBrokerage() { - response = HttpMethed.sendCoin(httpnode, fromAddress, witnessAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage - response = HttpMethed.updateBrokerage(httpnode, witnessAddress, 11L, witnessKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.sendCoin(httpnode, fromAddress, witnessAddress2, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible true - response = HttpMethed - .updateBrokerageOnVisible(httpnode, witnessAddress2, 24L, witnessKey2, "true"); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible false - response = HttpMethed - .updateBrokerageOnVisible(httpnode, witnessAddress, 88L, witnessKey, "false"); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible false for notwitness - response = HttpMethed.sendCoin(httpnode, fromAddress, dev001Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.updateBrokerageOnVisible(httpnode, dev001Address, 78L, dev001Key, "true"); - Assert.assertFalse(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward by http") - public void test05GetReward() { - response = HttpMethed.getReward(httpnode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardOnVisible(httpnode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardOnVisible(httpnode, witnessAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward from solidity by http") - public void test06GetRewardFromSolidity() { - response = HttpMethed.getRewardFromSolidity(httpSoliditynode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardFromSolidityOnVisible(httpSoliditynode, witnessAddress, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardFromSolidityOnVisible(httpSoliditynode, witnessAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward from PBFT by http") - public void test07GetRewardFromPbft() { - response = HttpMethed.getRewardFromPbft(httpPbftNode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0")) == 0) - || (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) - == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - //update brokerage - HttpMethed.freedResource(httpnode, witnessAddress, fromAddress, witnessKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java deleted file mode 100644 index 09ba3d8c737..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java +++ /dev/null @@ -1,224 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class HttpTestMutiSign001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String manager1Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] manager1Address = PublicMethed.getFinalAddress(manager1Key); - private final String manager2Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] manager2Address = PublicMethed.getFinalAddress(manager2Key); - private final String manager3Key = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] manager3Address = PublicMethed.getFinalAddress(manager3Key); - private final String manager4Key = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] manager4Address = PublicMethed.getFinalAddress(manager4Key); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] hexTestAddress = ecKey2.getAddress(); - String hexTestKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String[] permissionKeyString; - Long amount = 1000000000L; - JsonArray keys = new JsonArray(); - JsonArray activeKeys = new JsonArray(); - JsonObject manager1Wight = new JsonObject(); - JsonObject manager2Wight = new JsonObject(); - JsonObject manager3Wight = new JsonObject(); - JsonObject manager4Wight = new JsonObject(); - JsonObject ownerObject = new JsonObject(); - JsonObject witnessObject = new JsonObject(); - JsonObject activeObject = new JsonObject(); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Account Permission Up Date by http") - public void test1AccountPermissionUpDate() { - PublicMethed.printAddress(ownerKey); - response = HttpMethed.sendCoin(httpnode, fromAddress, ownerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - manager1Wight.addProperty("address", ByteArray.toHexString(manager1Address)); - manager1Wight.addProperty("weight", 1); - - logger.info(manager1Wight.toString()); - manager2Wight.addProperty("address", ByteArray.toHexString(manager2Address)); - manager2Wight.addProperty("weight", 1); - - logger.info(manager2Wight.toString()); - - keys.add(manager1Wight); - keys.add(manager2Wight); - - ownerObject.addProperty("type", 0); - ownerObject.addProperty("permission_name", "owner"); - ownerObject.addProperty("threshold", 2); - ownerObject.add("keys", keys); - - manager3Wight.addProperty("address", ByteArray.toHexString(manager3Address)); - manager3Wight.addProperty("weight", 1); - - logger.info(manager3Wight.toString()); - manager4Wight.addProperty("address", ByteArray.toHexString(manager4Address)); - manager4Wight.addProperty("weight", 1); - - logger.info(manager4Wight.toString()); - - activeKeys.add(manager3Wight); - activeKeys.add(manager4Wight); - - activeObject.addProperty("type", 2); - activeObject.addProperty("permission_name", "active0"); - activeObject.addProperty("threshold", 2); - activeObject.addProperty("operations", - "7fff1fc0037e0000000000000000000000000000000000000000000000000000"); - activeObject.add("keys", activeKeys); - - response = HttpMethed - .accountPermissionUpdate(httpnode, ownerAddress, ownerObject, witnessObject, activeObject, - ownerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Add transaction sign by http with permission id") - public void test2AddTransactionSign() { - - HttpMethed.waitToProduceOneBlock(httpnode); - permissionKeyString = new String[2]; - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - - String[] permissionKeyActive = new String[2]; - permissionKeyActive[0] = manager3Key; - permissionKeyActive[1] = manager4Key; - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 10L, 0, permissionKeyString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 10L, 2, permissionKeyString); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - logger.info("start permission id 2"); - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 12L, 2, permissionKeyActive); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 12L, 0, permissionKeyActive); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 11L, 1, permissionKeyActive); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 11L, 3, permissionKeyString); - Assert.assertFalse(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Add broadcasthex http interface to " - + "broadcast hex transaction string") - public void test3Broadcasthex() { - PublicMethed.printAddress(hexTestKey); - String transactionHex = PublicMethed - .sendcoinGetTransactionHex(hexTestAddress, 1000L, fromAddress, testKey002, - blockingStubFull); - - //Wrong type of hex - response = HttpMethed.broadcasthex(httpnode, transactionHex); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - String wrongTransactionHex = transactionHex + "wrong"; - response = HttpMethed.broadcasthex(httpnode, wrongTransactionHex); - logger.info("transaction wrong:"); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //SingleSign for broadcastHex - response = HttpMethed.broadcasthex(httpnode, transactionHex); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //Mutisign for broadcastHex - String mutiSignTransactionHex = PublicMethedForMutiSign - .sendcoinGetTransactionHex(hexTestAddress, 999L, ownerAddress, ownerKey, blockingStubFull, - permissionKeyString); - response = HttpMethed.broadcasthex(httpnode, mutiSignTransactionHex); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - //Hex is null - response = HttpMethed.broadcasthex(httpnode, ""); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java deleted file mode 100644 index 8fdaa8ddaa3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestProposal001 { - - private static Integer proposalId; - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = - Configuration.getByPath("testng.conf").getString("witness.key1"); - private final byte[] witness1Address = PublicMethed.getFinalAddress(witnessKey001); - private final String witnessKey002 = - Configuration.getByPath("testng.conf").getString("witness.key2"); - private final byte[] witness2Address = PublicMethed.getFinalAddress(witnessKey002); - private String httpnode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - private JSONObject responseContent; - private HttpResponse response; - - /** constructor. */ - @Test(enabled = true, description = "Create proposal by http") - public void test1CreateProposal() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.createProposal(httpnode, witness1Address, 21L, 1L, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** * constructor. * */ - @Test(enabled = true, description = "List proposals by http") - public void test2ListProposals() { - response = HttpMethed.listProposals(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("proposals")); - Assert.assertTrue(jsonArray.size() >= 1); - proposalId = jsonArray.size(); - } - - /** constructor. */ - @Test(enabled = true, description = "GetProposalById by http") - public void test3GetExchangeById() { - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("proposal_id") == proposalId); - Assert.assertEquals( - responseContent.getString("proposer_address"), ByteArray.toHexString(witness1Address)); - } - - /** constructor. */ - @Test(enabled = true, description = "Approval proposal by http") - public void test4ApprovalProposal() { - response = - HttpMethed.approvalProposal(httpnode, witness1Address, proposalId, true, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = - HttpMethed.approvalProposal(httpnode, witness2Address, proposalId, true, witnessKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("approvals")); - Assert.assertTrue(jsonArray.size() == 2); - } - - /** * constructor. * */ - @Test(enabled = true, description = "Get paginated proposal list by http") - public void test5GetPaginatedProposalList() { - - response = HttpMethed.getPaginatedProposalList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("proposals")); - Assert.assertTrue(jsonArray.size() == 1); - } - - /** constructor. */ - @Test(enabled = true, description = "Delete proposal by http") - public void test6DeleteProposal() { - response = HttpMethed.deleteProposal(httpnode, witness1Address, proposalId, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("state"), "CANCELED"); - } - - /** constructor. */ - @Test(enabled = true, description = "Get chain parameters by http") - public void test7GetChainParameters() { - response = HttpMethed.getChainParameters(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals( - "getMaintenanceTimeInterval", - responseContent.getJSONArray("chainParameter").getJSONObject(0).get("key")); - Assert.assertEquals( - 300000, responseContent.getJSONArray("chainParameter").getJSONObject(0).get("value")); - Assert.assertEquals( - "getCreateAccountFee", - responseContent.getJSONArray("chainParameter").getJSONObject(2).get("key")); - Assert.assertEquals( - 100000, responseContent.getJSONArray("chainParameter").getJSONObject(2).get("value")); - } - /** constructor. */ - - @Test(enabled = true, description = "Get energy price by http") - public void test8GetEnergyPrice() { - response = HttpMethed.getEnergyPric(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String prices = responseContent.getString("prices"); - String expectPrices = "0:100"; - logger.info("prices:" + prices); - Assert.assertEquals(prices, expectPrices); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java deleted file mode 100644 index 5741bcc6d65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java +++ /dev/null @@ -1,164 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestSendCoin001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 1000L; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @Test(enabled = true, description = "SendCoin by http") - public void test1SendCoin() { - response = HttpMethed.sendCoin(httpnode, fromAddress, receiverAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Assert.assertEquals(HttpMethed.getBalance(httpnode, receiverAddress), amount); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from solidity by http") - public void test2GetTransactionByIdFromSolidity() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - - response = HttpMethed.getTransactionByIdFromSolidity(httpSoliditynode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String retString = responseContent.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() > 4); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT by http") - public void test3GetTransactionByIdFromPbft() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - - response = HttpMethed.getTransactionByIdFromPbft(httpPbftNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String retString = responseContent.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() > 4); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by id from solidity by http") - public void test4GetTransactionInfoByIdFromSolidity() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getTransactionInfoByIdFromSolidity(httpSoliditynode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 4); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by id from PBFT by http") - public void test5GetTransactionInfoByIdFromPbft() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getTransactionInfoByIdFromPbft(httpPbftNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 4); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Get transactions from this from solidity by http") - public void test4GetTransactionsFromThisFromSolidity() { - response = HttpMethed - .getTransactionsFromThisFromSolidity(httpSoliditynode, fromAddress, 0, 100); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject transactionObject = HttpMethed.parseStringContent( - JSONArray.parseArray(responseContent.getString("transaction")).get(0).toString()); - String retString = transactionObject.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() == 1); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get transactions to this from solidity by http") - public void test5GetTransactionsToThisFromSolidity() { - response = HttpMethed - .getTransactionsFromThisFromSolidity(httpSoliditynode, fromAddress, 0, 100); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject transactionObject = HttpMethed.parseStringContent( - JSONArray.parseArray(responseContent.getString("transaction")).get(0).toString()); - String retString = transactionObject.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() == 1); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, receiverAddress, fromAddress, receiverKey); - HttpMethed.disConnect(); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java deleted file mode 100644 index 8f1d7c17ee7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestSmartContract001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] assetReceiverAddress = ecKey3.getAddress(); - String assetReceiverKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - String contractAddress; - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpRealSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(3); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy smart contract by http") - public void test1DeployContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetReceiverAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed - .freezeBalance(httpnode, assetOwnerAddress, 100000000L, 3, 1, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.assetIssue(httpnode, assetOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, assetOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - assetIssueId = responseContent.getString("asset_issued_ID"); - - contractName = "transferTokenContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractTrcToken001_transferTokenContract"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractTrcToken001_transferTokenContract"); - - long tokenValue = 100000; - long callValue = 5000; - - //This deploy is test too large call_token_value will made the witness node cpu 100% - /*response = HttpMethed.deployContractGetTxidWithTooBigLong(httpnode, - contractName, abi, code, 1000000L,1000000000L, 100, 11111111111111L, - callValue, Integer.parseInt(assetIssueId), tokenValue, assetOwnerAddress, assetOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertTrue(responseContent.getString("Error").contains("Overflow"));*/ - - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, callValue, Integer.parseInt(assetIssueId), tokenValue, - assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test2GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test3TriggerContract() { - - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info(addressParam); - logger.info(tokenIdParam); - logger.info(tokenValueParam); - final Long beforeBalance = HttpMethed.getBalance(httpnode, assetOwnerAddress); - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - //String txid = "49a30653d6e648da1e9a104b051b1b55c185fcaa0c2885405ae1d2fb258e3b3c"; - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(txid, responseContent.getString("txID")); - Assert.assertTrue(!responseContent.getString("raw_data").isEmpty()); - Assert.assertTrue(!responseContent.getString("raw_data_hex").isEmpty()); - Long afterBalance = HttpMethed.getBalance(httpnode, assetOwnerAddress); - logger.info("beforeBalance: " + beforeBalance); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance - afterBalance == callValue); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - Assert.assertTrue(HttpMethed.parseStringContent(receiptString).getLong("energy_usage") > 0); - Assert.assertTrue(responseContent.getLong("blockNumber") > 0); - - response = HttpMethed.getAccount(httpnode, assetReceiverAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("assetV2").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http") - public void test4GetTransactionInfoByBlocknum() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknum(httpnode, responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http from solidity") - public void test5GetTransactionInfoByBlocknumFromSolidity() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknumFromSolidity(httpSolidityNode, - responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http from real solidity") - public void test6GetTransactionInfoByBlocknumFromRealSolidity() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpRealSolidityNode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknumFromSolidity(httpRealSolidityNode, - responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateSetting contract by http") - public void test7UpdateSetting() { - - //assetOwnerAddress, assetOwnerKey - response = HttpMethed - .updateSetting(httpnode, assetOwnerAddress, contractAddress, 75, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "75"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateEnergyLimit contract by http") - public void test8UpdateEnergyLimit() { - - //assetOwnerAddress, assetOwnerKey - response = HttpMethed - .updateEnergyLimit(httpnode, assetOwnerAddress, contractAddress, 1234567, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "75"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "1234567"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.freedResource(httpnode, assetReceiverAddress, fromAddress, assetReceiverKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java deleted file mode 100644 index 58c09f1836d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java +++ /dev/null @@ -1,100 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestTransactionPending001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid; - JSONObject transaction; - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction pending size by http") - public void test01GetTransactionPendingSize() { - int pendingSize = 0; - int retryTimes = 50; - - while (pendingSize == 0 && retryTimes-- > 0) { - HttpMethed.sendCoin(httpnode,fromAddress,receiverAddress,1L,testKey002); - if (retryTimes % 5 == 0) { - pendingSize = HttpMethed.getTransactionPendingSize(httpnode); - } - } - - Assert.assertNotEquals(pendingSize,0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get pending transaction list by http") - public void test02GetPendingTransactionList() { - int transactionSize = 0; - int retryTimes = 50; - - while (transactionSize == 0 && retryTimes-- > 0) { - HttpMethed.sendCoin(httpnode,fromAddress,receiverAddress,1L,testKey002); - if (retryTimes % 5 == 0) { - response = HttpMethed.getTransactionListFromPending(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - transactionSize = responseContent.getJSONArray("txId").size(); - } - } - Assert.assertNotEquals(transactionSize,0); - - txid = responseContent.getJSONArray("txId").getString(0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction from pending by http") - public void test03GetPendingTransactionList() { - response = HttpMethed.getTransactionFromPending(httpnode,txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - Assert.assertEquals(txid,responseContent.getString("txID")); - Assert.assertNotEquals(null,responseContent); - } - - - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java deleted file mode 100644 index bb070512fe7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java +++ /dev/null @@ -1,382 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken001 { - - List shieldOutList = new ArrayList<>(); - Optional shieldAddressOptionalInfo1; - Optional shieldAddressOptionalInfo2; - Optional shieldAddressOptionalInfo3; - ShieldAddressInfo shieldAddressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo3 = new ShieldAddressInfo(); - String assetIssueId; - ShieldNoteInfo shieldNote1; - ShieldNoteInfo shieldNote2; - ShieldNoteInfo shieldNote3; - String memo; - String sk; - String d1; - String d2; - String d3; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String pkD2; - String pkD3; - String paymentAddress1; - String paymentAddress2; - String paymentAddress3; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private String tokenId = zenTokenId; - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = false, description = "Get spending key by http") - public void test01GetSpendingKey() { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sk = responseContent.getString("value"); - logger.info("sk: " + sk); - - } - - @Test(enabled = false, description = "Get diversifier by http") - public void test02GetDiversifier() { - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d1 = responseContent.getString("d"); - logger.info("d1: " + d1); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d2 = responseContent.getString("d"); - logger.info("d2: " + d2); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d3 = responseContent.getString("d"); - logger.info("d3: " + d3); - } - - @Test(enabled = false, description = "Get expanded spending key by http") - public void test03GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - logger.info("ask: " + ask); - logger.info("nsk: " + nsk); - logger.info("ovk: " + ovk); - } - - @Test(enabled = false, description = "Get AK from ASK by http") - public void test04GetAkFromAsk() { - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ak = responseContent.getString("value"); - logger.info("ak: " + ak); - } - - @Test(enabled = false, description = "Get Nk from Nsk by http") - public void test05GetNkFromNsk() { - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - nk = responseContent.getString("value"); - logger.info("nk: " + nk); - } - - @Test(enabled = false, description = "Get incoming viewing Key by http") - public void test06GetIncomingViewingKey() { - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ivk = responseContent.getString("ivk"); - logger.info("ivk: " + ivk); - } - - @Test(enabled = false, description = "Get Zen Payment Address by http") - public void test07GetZenPaymentAddress() { - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - System.out.println("pkd1: " + pkD1); - System.out.println("address1: " + paymentAddress1); - shieldAddressInfo1.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo1.setD(new DiversifierT(ByteArray.fromHexString(d1))); - shieldAddressInfo1.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo1.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo1.setPkD(ByteArray.fromHexString(pkD1)); - shieldAddressOptionalInfo1 = Optional.of(shieldAddressInfo1); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD2 = responseContent.getString("pkD"); - paymentAddress2 = responseContent.getString("payment_address"); - System.out.println("pkd2: " + pkD2); - System.out.println("address2: " + paymentAddress2); - shieldAddressInfo2.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo2.setD(new DiversifierT(ByteArray.fromHexString(d2))); - shieldAddressInfo2.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo2.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo2.setPkD(ByteArray.fromHexString(pkD2)); - shieldAddressOptionalInfo2 = Optional.of(shieldAddressInfo2); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d3); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD3 = responseContent.getString("pkD"); - paymentAddress3 = responseContent.getString("payment_address"); - System.out.println("pkd3: " + pkD3); - System.out.println("address3: " + paymentAddress3); - shieldAddressInfo3.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo3.setD(new DiversifierT(ByteArray.fromHexString(d3))); - shieldAddressInfo3.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo3.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo3.setPkD(ByteArray.fromHexString(pkD3)); - shieldAddressOptionalInfo3 = Optional.of(shieldAddressInfo3); - } - - @Test(enabled = false, description = "Get rcm by http") - public void test08GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - @Test(enabled = false, description = "Public to shield transaction withoutask by http") - public void test09PublicToShieldTransactionWithoutAsk() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - String memo1 = "Shield memo11 in " + System.currentTimeMillis(); - String memo2 = "Shield memo22 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount1 = zenTokenFee * 2; - Long sendSheldAddressAmount2 = zenTokenFee * 3; - Long sendAmount = sendSheldAddressAmount1 + sendSheldAddressAmount2 + zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo1.get().getAddress(), - "" + sendSheldAddressAmount1, memo1); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo2.get().getAddress(), - "" + sendSheldAddressAmount2, memo2); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, zenTokenOwnerAddress, - sendAmount, null, null, shieldOutList, null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - String memo3 = "Shield memo33 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount3 = costTokenAmount - sendAmount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo3.get().getAddress(), - "" + sendSheldAddressAmount3, memo3); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, zenTokenOwnerAddress, - sendSheldAddressAmount3 + zenTokenFee, null, null, shieldOutList, null, 0, - zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - List shieldNoteInfoByIvkList = HttpMethed - .scanNoteByIvk(httpnode, shieldAddressOptionalInfo1.get()); - logger.info("size are:" + shieldNoteInfoByIvkList.size()); - Assert.assertTrue(shieldNoteInfoByIvkList.size() == 3); - List shieldNoteInfoByMarkList = HttpMethed - .scanAndMarkNoteByIvk(httpnode, shieldAddressOptionalInfo2.get()); - Assert.assertTrue(shieldNoteInfoByMarkList.size() == 3); - - shieldNote1 = shieldNoteInfoByIvkList.get(0); - shieldNote2 = shieldNoteInfoByIvkList.get(1); - shieldNote3 = shieldNoteInfoByIvkList.get(2); - Assert.assertTrue(shieldNote1.getValue() == sendSheldAddressAmount1); - Assert.assertEquals(memo1.getBytes(), shieldNote1.getMemo()); - Assert.assertTrue(shieldNote2.getValue() == sendSheldAddressAmount2); - Assert.assertEquals(memo2.getBytes(), shieldNote2.getMemo()); - Assert.assertTrue(shieldNote3.getValue() == sendSheldAddressAmount3); - Assert.assertEquals(memo3.getBytes(), shieldNote3.getMemo()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(0).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(1).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(2).getIsSpend()); - } - - @Test(enabled = false, description = "Shield to shield transaction withoutask by http") - public void test10ShieldToShieldTransactionWithoutAsk() { - Optional receiverShieldAddressInfo1 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - Optional receiverShieldAddressInfo2 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - Optional receiverShieldAddressInfo3 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - logger.info("receiverShieldAddress3:" + receiverShieldAddress3); - - shieldOutList.clear(); - String receiverMemo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + (shieldNote1.getValue() - zenTokenFee), receiverMemo1); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - shieldAddressOptionalInfo1.get(), shieldNote1, shieldOutList, null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - /*shieldOutList.clear(); - String receiverMemo2 = "Shield memo2 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + (shieldNote2.getValue() - zenTokenFee), receiverMemo2); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, null, 0, shieldAddressOptionalInfo2.get(), shieldNote2, - shieldOutList, - null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent);*/ - shieldOutList.clear(); - String receiverMemo3 = "Shield memo3 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + (shieldNote3.getValue() - zenTokenFee), receiverMemo3); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - shieldAddressOptionalInfo3.get(), shieldNote3, shieldOutList, null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - List shieldNoteInfoByOvkList = HttpMethed - .scanNoteByOvk(httpnode, shieldAddressOptionalInfo3.get()); - Assert.assertTrue(shieldNoteInfoByOvkList.size() == 2); - List shieldNoteInfoByMarkList = HttpMethed - .scanAndMarkNoteByIvk(httpnode, shieldAddressOptionalInfo2.get()); - Assert.assertTrue(shieldNoteInfoByMarkList.size() == 3); - - Assert.assertTrue( - shieldNoteInfoByOvkList.get(0).getValue() == shieldNote1.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo1.getBytes(), shieldNoteInfoByOvkList.get(0).getMemo()); - /*Assert.assertTrue( - shieldNoteInfoByOvkList.get(1).getValue() == shieldNote2.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo2.getBytes(), shieldNoteInfoByOvkList.get(1).getMemo());*/ - Assert.assertTrue( - shieldNoteInfoByOvkList.get(1).getValue() == shieldNote3.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo3.getBytes(), shieldNoteInfoByOvkList.get(1).getMemo()); - Assert.assertTrue(shieldNoteInfoByMarkList.get(0).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(1).getIsSpend()); - Assert.assertTrue(shieldNoteInfoByMarkList.get(2).getIsSpend()); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java deleted file mode 100644 index 7355cff0dfe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java +++ /dev/null @@ -1,332 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken002 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiverNote; - ShieldNoteInfo noteByOvk; - ShieldNoteInfo noteByIvk; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long sendTokenAmount = 7 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Args.setFullNodeAllowShieldedTransaction(true); - - } - - @Test(enabled = false, description = "Public to shield transaction by http") - public void test01PublicToShieldTransaction() { - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo1); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(sendNote.getValue() == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo1.getBytes(), sendNote.getMemo()); - - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteSendNote.getIsSpend()); - } - - @Test(enabled = false, description = "Shield to shield transaction by http") - public void test02ShieldToShieldTransaction() { - receiverShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo2 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo2); - - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - receiverNote = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - - Assert.assertTrue(receiverNote.getValue() == sendNote.getValue() - zenTokenFee); - Assert.assertEquals(ByteArray.toHexString(memo2.getBytes()), - ByteArray.toHexString(receiverNote.getMemo())); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - Assert.assertFalse( - HttpMethed.getSpendResult(httpnode, receiverShieldAddressInfo.get(), receiverNote)); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on FullNode by http") - public void test03ScanNoteByIvkAndOvk() { - //Scan sender note by ovk equals scan receiver note by ivk on FullNode - noteByOvk = HttpMethed.scanNoteByOvk(httpnode, sendShieldAddressInfo.get()).get(0); - noteByIvk = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on Solidity by http") - public void test04ScanNoteByIvkAndOvkFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - //Scan sender note by ovk equals scan receiver note by ivk on Solidity - noteByOvk = HttpMethed.scanNoteByOvkFromSolidity(httpSolidityNode, sendShieldAddressInfo.get()) - .get(0); - noteByIvk = HttpMethed - .scanNoteByIvkFromSolidity(httpSolidityNode, receiverShieldAddressInfo.get()).get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on PBFT by http") - public void test05ScanNoteByIvkAndOvkFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - //Scan sender note by ovk equals scan receiver note by ivk on Solidity - noteByOvk = HttpMethed.scanNoteByOvkFromPbft(httpPbftNode, sendShieldAddressInfo.get()).get(0); - noteByIvk = HttpMethed.scanNoteByIvkFromPbft(httpPbftNode, receiverShieldAddressInfo.get()) - .get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on solidity by http") - public void test06QueryNoteIsSpendOnSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get(), - sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, receiverShieldAddressInfo.get(), - receiverNote)); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on PBFT by http") - public void test07QueryNoteIsSpendOnSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromPbft(httpnode, httpPbftNode, sendShieldAddressInfo.get(), sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromPbft(httpnode, httpPbftNode, receiverShieldAddressInfo.get(), - receiverNote)); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query note and spend status on fullnode") - public void test08QueryNoteAndSpendStatusOnFullnode() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - } - - @Test(enabled = false, description = "Query note and spend status on solidity") - public void test09QueryNoteAndSpendStatusOnSolidity() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvkFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get()) - .get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvkFromSolidity(httpnode, httpSolidityNode, - receiverShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - - } - - @Test(enabled = false, description = "Query note and spend status on PBFT") - public void test10QueryNoteAndSpendStatusOnPbft() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvkFromPbft(httpnode, httpPbftNode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvkFromPbft(httpnode, httpPbftNode, receiverShieldAddressInfo.get()) - .get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - - } - - - @Test(enabled = false, description = "Shield to public transaction by http") - public void test11ShieldToPublicTransaction() { - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, receiverShieldAddressInfo.get(), receiverNote, - shieldOutList, zenTokenOwnerAddress, receiverNote.getValue() - zenTokenFee, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue( - afterAssetBalance - beforeAssetBalance == receiverNote.getValue() - zenTokenFee); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - Assert.assertTrue( - HttpMethed.getSpendResult(httpnode, receiverShieldAddressInfo.get(), receiverNote)); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java deleted file mode 100644 index ca1889b0423..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java +++ /dev/null @@ -1,308 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken003 { - - Optional receiverShieldAddressInfo1; - Optional receiverShieldAddressInfo2; - Optional receiverShieldAddressInfo3; - Optional receiverShieldAddressInfo4; - Optional receiverShieldAddressInfo5; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - String receiverShieldAddress4; - String receiverShieldAddress5; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - String memo3; - String memo4; - String memo5; - ShieldNoteInfo receiverNote1; - ShieldNoteInfo receiverNote2; - ShieldNoteInfo receiverNote3; - ShieldNoteInfo receiverNote4; - ShieldNoteInfo receiverNote5; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long sendTokenAmount = 18 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - Args.setFullNodeAllowShieldedTransaction(true); - - } - - @Test(enabled = false, description = "Public to two shield transaction by http") - public void test01PublicToTwoShieldTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo1 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddressInfo2 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = sendTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote1 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo1.get()).get(0); - receiverNote2 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo2.get()).get(0); - Assert.assertTrue(receiverNote1.getValue() == sendToShiledAddress1Amount); - Assert.assertTrue(receiverNote2.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo1.getBytes(), receiverNote1.getMemo()); - Assert.assertEquals(memo2.getBytes(), receiverNote2.getMemo()); - } - - @Test(enabled = false, description = "Public to one public and one shield transaction by http") - public void test02ShieldToOneShieldAndOnePublicTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo3 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - - final Long beforeAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long beforeBalanceSendAddress = responseContent.getLong("balance"); - - final Long beforeAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddressAmount = - sendTokenAmount - sendToPublicAddressAmount - zenTokenWhenCreateNewAddress; - memo3 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + sendToShiledAddressAmount, memo3); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterBalanceSendAddress = responseContent.getLong("balance"); - - final Long afterAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue( - beforeAssetBalanceSendAddress - afterAssetBalanceSendAddress == sendTokenAmount); - Assert.assertTrue(beforeNetUsedSendAddress == afterNetUsedSendAddress); - Assert.assertTrue(beforeBalanceSendAddress == afterBalanceSendAddress); - - Assert.assertTrue(afterAssetBalanceReceiverAddress - beforeAssetBalanceReceiverAddress - == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsedReceiverAddress == afterNetUsedReceiverAddress); - - receiverNote3 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0); - - Assert.assertTrue(receiverNote3.getValue() == sendToShiledAddressAmount); - Assert.assertEquals(memo3.getBytes(), receiverNote3.getMemo()); - } - - @Test(enabled = false, description = "Public to one public and two shield transaction by http") - public void test03ShieldToOneShieldAndTwoPublicTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo4 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress4 = receiverShieldAddressInfo4.get().getAddress(); - receiverShieldAddressInfo5 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress5 = receiverShieldAddressInfo5.get().getAddress(); - - final Long beforeAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long beforeBalanceSendAddress = responseContent.getLong("balance"); - - final Long beforeAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddress1Amount = 2 * zenTokenFee; - Long sendToShiledAddress2Amount = - sendTokenAmount - sendToPublicAddressAmount - sendToShiledAddress1Amount - zenTokenFee; - memo4 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - memo5 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress4, - "" + sendToShiledAddress1Amount, memo4); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress5, - "" + sendToShiledAddress2Amount, memo5); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterBalanceSendAddress = responseContent.getLong("balance"); - - final Long afterAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue( - beforeAssetBalanceSendAddress - afterAssetBalanceSendAddress == sendTokenAmount); - Assert.assertTrue(beforeNetUsedSendAddress == afterNetUsedSendAddress); - Assert.assertTrue(beforeBalanceSendAddress == afterBalanceSendAddress); - - Assert.assertTrue(afterAssetBalanceReceiverAddress - beforeAssetBalanceReceiverAddress - == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsedReceiverAddress == afterNetUsedReceiverAddress); - - receiverNote4 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo4.get()).get(0); - Assert.assertTrue(receiverNote4.getValue() == sendToShiledAddress1Amount); - Assert.assertEquals(memo4.getBytes(), receiverNote4.getMemo()); - - receiverNote5 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo5.get()).get(0); - Assert.assertTrue(receiverNote5.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo5.getBytes(), receiverNote5.getMemo()); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance1 = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance1, zenTokenOwnerKey); - - final Long assetBalance2 = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, receiverPublicAddress, foundationZenTokenAddress, assetIssueId, - assetBalance2, receiverPublicKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java deleted file mode 100644 index d7d9bcb6e5d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java +++ /dev/null @@ -1,289 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken004 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo1; - Optional receiverShieldAddressInfo2; - Optional receiverShieldAddressInfo3; - Optional receiverShieldAddressInfo4; - Optional receiverShieldAddressInfo5; - String sendShieldAddress; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - String receiverShieldAddress4; - String receiverShieldAddress5; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - String memo3; - String memo4; - String memo5; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiverNote1; - ShieldNoteInfo receiverNote2; - ShieldNoteInfo receiverNote3; - ShieldNoteInfo receiverNote4; - ShieldNoteInfo receiverNote5; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey1.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long sendTokenAmount = 18 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, description = "Shield to two shield transaction by http") - public void test01ShieldToTwoShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo1 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddressInfo2 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = sendTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverNote1 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo1.get()).get(0); - receiverNote2 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo2.get()).get(0); - Assert.assertTrue(receiverNote1.getValue() == sendToShiledAddress1Amount); - Assert.assertTrue(receiverNote2.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo1.getBytes(), receiverNote1.getMemo()); - Assert.assertEquals(memo2.getBytes(), receiverNote2.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - @Test(enabled = false, description = "Shield to one public and one shield transaction by http") - public void test02ShieldToOnePublicAndOneShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo3 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddressAmount = - sendTokenAmount - sendToPublicAddressAmount - zenTokenWhenCreateNewAddress; - memo3 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + sendToShiledAddressAmount, memo3); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - final Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote3 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0); - Assert.assertTrue(receiverNote3.getValue() == sendToShiledAddressAmount); - Assert.assertEquals(memo3.getBytes(), receiverNote3.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get(), - sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, receiverShieldAddressInfo3.get(), - receiverNote3)); - - Assert.assertTrue( - HttpMethed.scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0).getIsSpend()); - Assert.assertFalse( - HttpMethed.scanAndMarkNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0) - .getIsSpend()); - } - - @Test(enabled = false, description = "Shield to one public and two shield transaction by http") - public void test03ShieldToOnePublicAndTwoShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo4 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress4 = receiverShieldAddressInfo4.get().getAddress(); - receiverShieldAddressInfo5 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress5 = receiverShieldAddressInfo5.get().getAddress(); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddress1Amount = 2 * zenTokenFee; - Long sendToShiledAddress2Amount = - sendTokenAmount - sendToPublicAddressAmount - sendToShiledAddress1Amount - zenTokenFee; - memo4 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - memo5 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress4, - "" + sendToShiledAddress1Amount, memo4); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress5, - "" + sendToShiledAddress2Amount, memo5); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - final Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote4 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo4.get()).get(0); - Assert.assertTrue(receiverNote4.getValue() == sendToShiledAddress1Amount); - Assert.assertEquals(memo4.getBytes(), receiverNote4.getMemo()); - - receiverNote5 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo5.get()).get(0); - Assert.assertTrue(receiverNote5.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo5.getBytes(), receiverNote5.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, receiverPublicAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, receiverPublicKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java deleted file mode 100644 index 2075fd37b8c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken005 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiveNote; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long sendTokenAmount = 7 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo1); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - shieldOutList.clear(); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - } - - @Test(enabled = false, description = "Shield to shield transaction without ask by http") - public void test01ShieldToShieldWithoutAskTransaction() { - receiverShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo2 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo2); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - sendShieldAddressInfo.get(), sendNote, shieldOutList, null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiveNote = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - - Assert.assertTrue(receiveNote.getValue() == sendNote.getValue() - zenTokenFee); - Assert.assertEquals(ByteArray.toHexString(memo2.getBytes()), - ByteArray.toHexString(receiveNote.getMemo())); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - @Test(enabled = false, description = "Get merkle tree voucher info by http") - public void test02GetMerkleTreeVoucherInfo() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .getMerkleTreeVoucherInfo(httpnode, sendNote.getTrxId(), sendNote.getIndex(), 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains("tree")); - Assert.assertTrue(responseContent.toJSONString().contains("rt")); - Assert.assertTrue(responseContent.toJSONString().contains("paths")); - - response = HttpMethed - .getMerkleTreeVoucherInfo(httpnode, receiveNote.getTrxId(), receiveNote.getIndex(), 1000); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains( - "synBlockNum is too large, cmBlockNum plus synBlockNum must be <= latestBlockNumber")); - } - - @Test(enabled = false, description = "Get merkle tree voucher info by http from solidity") - public void test03GetMerkleTreeVoucherInfoFromSolidity() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, sendNote.getTrxId(), - sendNote.getIndex(), 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains("tree")); - Assert.assertTrue(responseContent.toJSONString().contains("rt")); - Assert.assertTrue(responseContent.toJSONString().contains("paths")); - - response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, receiveNote.getTrxId(), - receiveNote.getIndex(), 1000); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains( - "synBlockNum is too large, cmBlockNum plus synBlockNum must be <= latestBlockNumber")); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java deleted file mode 100644 index 8cb5b71a406..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestZenToken006 { - - List shieldOutList = new ArrayList<>(); - String assetIssueId; - String sk; - String d1; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String paymentAddress1; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private String tokenId = zenTokenId; - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = false, description = "Get new shielded address by http") - public void test01GetNewShieldedAddress() { - response = HttpMethed.getNewShieldedAddress(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 10); - Assert.assertTrue(responseContent.containsKey("d")); - Assert.assertTrue(responseContent.containsKey("ovk")); - Assert.assertTrue(responseContent.containsKey("nsk")); - Assert.assertTrue(responseContent.containsKey("payment_address")); - Assert.assertTrue(responseContent.containsKey("sk")); - Assert.assertTrue(responseContent.containsKey("ask")); - Assert.assertTrue(responseContent.containsKey("pkD")); - Assert.assertTrue(responseContent.containsKey("ak")); - Assert.assertTrue(responseContent.containsKey("nk")); - Assert.assertTrue(responseContent.containsKey("ivk")); - - sk = responseContent.getString("sk"); - d1 = responseContent.getString("d"); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - ak = responseContent.getString("ak"); - nk = responseContent.getString("nk"); - ivk = responseContent.getString("ivk"); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - } - - @Test(enabled = false, description = "Get expanded spending key by http") - public void test02GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String askFromSk = responseContent.getString("ask"); - String nskFromSk = responseContent.getString("nsk"); - String ovkFromSk = responseContent.getString("ovk"); - Assert.assertEquals(ask, askFromSk); - Assert.assertEquals(nsk, nskFromSk); - Assert.assertEquals(ovk, ovkFromSk); - - } - - - @Test(enabled = false, description = "Get rcm by http") - public void test03GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - @Test(enabled = false, description = "Public to shield transaction withoutask by http") - public void test04PublicToShieldTransactionWithoutAsk() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - String memo1 = "Shield memo11 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount1 = zenTokenFee * 2; - Long sendAmount = sendSheldAddressAmount1 + zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, paymentAddress1, "" + sendSheldAddressAmount1, - memo1); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpnode, zenTokenOwnerAddress, - sendAmount, null, null, shieldOutList, null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java deleted file mode 100644 index 4bb08861889..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java +++ /dev/null @@ -1,503 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractInternalTransaction001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Create->call.Two-level nesting") - public void testInternalTransaction001() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction001.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(7, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - String initParmes2 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes2, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(10, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById1.get().getInternalTransactions(i).getRejected()); - } - } - - @Test(enabled = true, description = "There is one internalTransaction.Only call") - public void testInternalTransaction002() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction002.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes2 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes2, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - Assert.assertFalse(infoById1.get().getInternalTransactions(0).getRejected()); - String note = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Assert.assertEquals("call", note); - Assert.assertEquals(1, - infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue()); - - } - - @Test(enabled = true, description = "There is one internalTransaction.Only create") - public void testInternalTransaction003() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction003.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - Assert.assertFalse(infoById1.get().getInternalTransactions(0).getRejected()); - String note = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Assert.assertEquals("create", note); - Assert.assertEquals(10, - infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue()); - - } - - @Test(enabled = true, description = "Test suicide type in internalTransaction") - public void testInternalTransaction004() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction004.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress) - + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress1, - "kill(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note); - Assert.assertEquals("suicide", note1); - Assert.assertTrue(0 == vaule1); - Assert.assertTrue(1000000L == vaule2); - - String txid1 = PublicMethed.triggerContract(contractAddress1, - "kill2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(2).getNote().toByteArray()); - Assert.assertEquals("create", note3); - Assert.assertEquals("call", note4); - Assert.assertEquals("suicide", note5); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals(0, - infoById1.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - - } - } - - @Test(enabled = true, description = "Type is create call") - public void testInternalTransaction005() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction005.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - - Long vaule3 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(10 == vaule3); - Assert.assertTrue(0 == vaule4); - Assert.assertEquals("create", note3); - Assert.assertEquals("call", note4); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - - - } - } - - @Test(enabled = true, description = "Type is create call call") - public void testInternalTransaction006() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction006.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("call", note2); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(0 == vaule3); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - String note6 = ByteArray - .toStr(infoById1.get().getInternalTransactions(2).getNote().toByteArray()); - Long vaule4 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule5 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule6 = infoById1.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - - Assert.assertTrue(10 == vaule4); - Assert.assertTrue(0 == vaule5); - Assert.assertTrue(0 == vaule6); - Assert.assertEquals("create", note4); - Assert.assertEquals("call", note5); - Assert.assertEquals("call", note6); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - } - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java deleted file mode 100644 index 0794f29dfa0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java +++ /dev/null @@ -1,580 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractInternalTransaction002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Type is create create call call") - public void test1InternalTransaction007() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test1InternalTransaction007.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertNotNull(infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(5 == vaule3); - Assert.assertTrue(0 == vaule4); - String initParmes1 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Long vaule5 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(1 == vaule5); - Assert.assertEquals("call", note5); - Assert.assertTrue(infoById1.get().getInternalTransactions(0).getRejected()); - - - } - - @Test(enabled = true, description = "Type is call call") - public void test2InternalTransaction008() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test2InternalTransaction008.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testAssert(address,uint256)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - Assert.assertTrue(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertFalse(infoById.get().getInternalTransactions(1).getRejected()); - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note); - Assert.assertEquals("call", note1); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(1 == vaule2); - String contractName2 = "C"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes1 = "\"" + Base58.encode58Check(contractAddress2) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "testRequire(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - Assert.assertTrue(infoById1.get().getInternalTransactions(0).getRejected()); - Assert.assertFalse(infoById1.get().getInternalTransactions(1).getRejected()); - String note2 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule3 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(1 == vaule3); - Assert.assertTrue(1 == vaule4); - - String txid2 = PublicMethed.triggerContract(contractAddress, - "testAssert1(address,uint256)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - int transactionsCount2 = infoById2.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount2); - dupInternalTrsansactionHash(infoById2.get().getInternalTransactionsList()); - Assert.assertFalse(infoById2.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById2.get().getInternalTransactions(1).getRejected()); - - String note5 = ByteArray - .toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray()); - String note6 = ByteArray - .toStr(infoById2.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule5 = infoById2.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule6 = infoById2.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note5); - Assert.assertEquals("call", note6); - Assert.assertTrue(1 == vaule5); - Assert.assertTrue(1 == vaule6); - - String txid3 = PublicMethed.triggerContract(contractAddress, - "testtRequire2(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - int transactionsCount3 = infoById3.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount3); - dupInternalTrsansactionHash(infoById3.get().getInternalTransactionsList()); - - Assert.assertFalse(infoById3.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById3.get().getInternalTransactions(1).getRejected()); - String note7 = ByteArray - .toStr(infoById3.get().getInternalTransactions(0).getNote().toByteArray()); - String note8 = ByteArray - .toStr(infoById3.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule7 = infoById3.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule8 = infoById3.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note7); - Assert.assertEquals("call", note8); - Assert.assertTrue(1 == vaule7); - Assert.assertTrue(1 == vaule8); - - } - - @Test(enabled = true, description = "Test suicide type in internalTransaction after call") - public void test3InternalTransaction009() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test3InternalTransaction009.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "C"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName3 = "D"; - HashMap retMap3 = PublicMethed.getBycodeAbi(filePath, contractName3); - String code3 = retMap3.get("byteCode").toString(); - String abi3 = retMap3.get("abI").toString(); - byte[] contractAddress3 = PublicMethed - .deployContract(contractName3, abi3, code3, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = "\"" + Base58.encode58Check(contractAddress2) - + "\",\"" + Base58.encode58Check(contractAddress3) + "\",\"" + Base58 - .encode58Check(contractAddress1) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(7, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(6).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("suicide", note2); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(5 == vaule2); - - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "test1(address,address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(6, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - } - - @Test(enabled = false, description = "Test maxfeelimit can trigger create type max time") - public void test4InternalTransaction010() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test4InternalTransaction010.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(76, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress, - "transfer2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(76, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById1.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById1.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - - } - - - } - - - @Test(enabled = true, description = "Type is call create->call->call.Three-level nesting") - public void test5InternalTransaction012() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test5InternalTransaction012.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap1.get("byteCode").toString(); - String abi2 = retMap1.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Assert.assertEquals("call", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(1000 == vaule2); - Assert.assertTrue(0 == vaule3); - Assert.assertTrue(1 == vaule4); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java deleted file mode 100644 index 1c7a94d3002..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java +++ /dev/null @@ -1,584 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Retry; - -@Slf4j - -public class ContractInternalTransaction003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Three-level nesting.Type is Create call->call->create") - public void testInternalTransaction013() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction013.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "D"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("create", note3); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(2 == vaule3); - Assert.assertTrue(5 == vaule4); - - - } - - - @Test(enabled = true, description = "Test delegatecall and callcode.") - public void testInternalTransaction014() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction014.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "sendToB(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(infoById.get().getInternalTransactions(0).getCallerAddress() - .toByteArray()), - ByteArray.toHexString( - infoById.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB2(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - int transactionsCount2 = infoById2.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount2); - for (int i = 0; i < transactionsCount2; i++) { - Assert.assertFalse(infoById2.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById2.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(contractAddress), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(0).getCallerAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress1), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress1), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(1).getCallerAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - - String txid3 = ""; - txid3 = PublicMethed.triggerContract(contractAddress, - "sendToB3(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - int transactionsCount3 = infoById3.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount3); - for (int i = 0; i < transactionsCount3; i++) { - Assert.assertFalse(infoById3.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById3.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(infoById3.get().getInternalTransactions(0).getCallerAddress() - .toByteArray()), - ByteArray.toHexString( - infoById3.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById3.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById2.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById3.get().getInternalTransactionsList()); - - } - - @Test(enabled = true, description = "Three-level nesting.Type " - + "is create call->call->create call->suicide") - public void testInternalTransaction015() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction015.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "D"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(6, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - - } - - - @Test(enabled = false, description = "After create 80 times,then suicide") - public void testInternalTransaction016() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction016.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(69, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - Assert.assertEquals("suicide", ByteArray - .toStr(infoById.get().getInternalTransactions(68).getNote().toByteArray())); - Assert.assertEquals("call", ByteArray - .toStr(infoById.get().getInternalTransactions(67).getNote().toByteArray())); - Assert.assertEquals(0, - infoById.get().getInternalTransactions(67).getCallValueInfo(0).getCallValue()); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(68).getCallValueInfo(0).getCallValue()); - for (int i = 0; i < transactionsCount - 2; i++) { - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "transfer2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - - Assert.assertEquals(68, transactionsCount1); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById1.get().getInternalTransactions(i).getNote().toByteArray())); - - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - } - - @Test(enabled = false, description = "After create 88 times,then suicide") - public void testInternalTransaction017() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction017.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress) + "\""; - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(77, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - Assert.assertEquals("suicide", ByteArray - .toStr(infoById.get().getInternalTransactions(76).getNote().toByteArray())); - Assert.assertEquals(1000000 - 76, - infoById.get().getInternalTransactions(76).getCallValueInfo(0).getCallValue()); - for (int i = 0; i < transactionsCount - 1; i++) { - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - } - - @Test(enabled = true,retryAnalyzer = Retry.class, - description = "Test maxfeelimit can trigger call create call max time") - public void testInternalTransaction018() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction018.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed - .sendcoin(internalTxsAddress, 2000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 100000, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById:" + infoById); - - int retryTimes = 1; - while (retryTimes++ < 5 && infoById.get().getResultValue() != 0) { - // retry 5 times - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 100000, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById retry " + retryTimes + " : " + infoById); - } - - - - Assert.assertEquals(0, infoById.get().getResultValue()); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(184, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - - Assert.assertEquals("call", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(100 == vaule2); - Assert.assertTrue(0 == vaule3); - Assert.assertTrue(1 == vaule4); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java deleted file mode 100644 index 174f6d1d8d2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java +++ /dev/null @@ -1,1225 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Accounts001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromJsonRpcNode = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromJsonRpcNode:" + blockNumFromJsonRpcNode); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromJsonRpcNode - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromJsonRpcNode = responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromJsonRpcNode:" + blockIdFromJsonRpcNode); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromJsonRpcNode, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameter(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - Long balance2 = HttpMethed.getBalance(httpFullNode, foundationAccountAddress); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNode, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("16blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumResult = responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("16indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("16requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("16transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("16jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknum(httpFullNode, blockNum); - logger.info("16response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("16responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), "0x" + getBlockByNumResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = getBlockByNumResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = Long.parseLong(getBlockByNumResult.getString("signature").substring(130, 131), 16); - long v = Long.parseLong(getBlockByNumResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; - } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumResult.getString("signature").substring(66, 130)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("17blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("17blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("17requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("17responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromJsonRpcNode = Integer.parseInt(transactionNum, 16); - logger.info("17transactionNumFromJsonRpcNode:" + transactionNumFromJsonRpcNode); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromJsonRpcNode); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - logger.info("20transacionHash:" + transacionHash); - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("20responseContent:" + responseContent); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - logger.info("trc20Txid:" + trc20Txid); - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("21requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("21response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("21resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("21logs:" + logs); - logger.info("21result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNode, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); - /* Assert.assertEquals( - resultFromTransactionReceipt.getString("contractAddress").substring(2), - trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = HttpMethed.getTransactionInfoByBlocknum(httpFullNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("21responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - String resultFromJsonRpcNode = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - String resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromJsonRpcNode:" + resultFromJsonRpcNode); - logger.info("resultFromHttp:" + resultFromHttp); - Assert.assertEquals(resultFromJsonRpcNode, resultFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - long currentNum = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("currentNum:" + currentNum); - logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening") - public void test31JsonRpcApiTestForNetListening() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - Boolean temp = responseContent.getBoolean("result"); - logger.info(temp.toString()); - response = HttpMethed.getNodeInfo(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - boolean expect = false; - int num = responseContent.getInteger("activeConnectCount"); - if (num >= 1) { - expect = true; - } - Assert.assertEquals(temp, expect); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); - } - - @Test(enabled = true, description = "Json rpc api of net_version") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNode, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("48getBlockByNumFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - if (accountStateRoot == null) { - accountStateRoot = ""; - } - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("48sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "48sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByNumber params is true") - public void test49JsonRpcApiTestForEthGetBlockByNumber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("49blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByNumberResult = responseContent.getJSONObject("result"); - logger.info("49getBlockByHashResult:" + getBlockByNumberResult); - - Assert.assertNull(getBlockByNumberResult.getString("nonce")); - Assert.assertNull(getBlockByNumberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumberResult.getString("extraData")); - Assert.assertNull(getBlockByNumberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumberResult.getString("mixHash")); - Assert.assertEquals(getBlockByNumberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByNumberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumberResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByNumberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByNumberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByNumberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong(getBlockByNumberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("49size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumberResult.getString("size").substring(2), 16), size); - - JSONArray transactionsList = getBlockByNumberResult.getJSONArray("transactions"); - logger.info("49transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("49index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNode, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("49responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("49result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java deleted file mode 100644 index e4d2407bdb4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ /dev/null @@ -1,1290 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Accounts002 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts from solidity") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber from solidity") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call from solidity") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId from solidity") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromjsonRpcNodeForSolidity = - responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase from solidity") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas from solidity") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoByIdFromSolidity(httpsolidityNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo from solidity") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx from solidity") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice from solidity") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameters(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance from solidity") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - logger.info("balance1:" + balance1); - response = HttpMethed.getAccountFromSolidity(httpsolidityNode, foundationAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long balance2 = responseContent.getLong("balance"); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByNumber from solidity") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCode from solidity") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt from solidity") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt from solidity") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex from solidity") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumFromSolidityResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumFromSolidityResult = - responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("13requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNum); - logger.info("response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), - "0x" + getBlockByNumFromSolidityResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = - getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); - long v = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; - } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByHash from solidity") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); - logger.info( - "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByNumber from solidity") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getTransactionByBlockHashAndIndex from solidity") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash from solidity") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt from solidity") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("logs:" + logs); - logger.info("result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); - /* Assert.assertEquals( - resultFromTransactionReceipt.getString("contractAddress").substring(2), - trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = - HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleByBlockHashAndIndex from solidity") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleByBlockNumberAndIndex from solidity") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash from solidity") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleCountByBlockNumber from solidity") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork from solidity") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - String resultFromjsonRpcNodeForSolidity = ""; - String resultFromHttp = ""; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromjsonRpcNodeForSolidity" + i + ":" + resultFromjsonRpcNodeForSolidity); - logger.info("resultFromHttp" + i + ":" + resultFromHttp); - if (resultFromjsonRpcNodeForSolidity.equals(resultFromHttp)) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate from solidity ") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining from solidity") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion from solidity") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing from solidity") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - long currentNumFromHttp = 0; - long currentNumFromJsonRpc = 0; - JSONObject temp = responseContent; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - currentNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - currentNumFromJsonRpc = Long.parseLong(currentNumFromRpc.substring(2), 16); - logger.info("currentNumFromHttp" + i + ":" + currentNumFromHttp); - logger.info("currentNumFromJsonRpc:" + currentNumFromJsonRpc); - if (currentNumFromHttp == currentNumFromJsonRpc) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(currentNumFromHttp, currentNumFromJsonRpc); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening from solidity") - public void test31JsonRpcApiTestForNetListening() throws Exception { - boolean temp = false; - boolean expect = false; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - temp = responseContent.getBoolean("result"); - response = HttpMethed.getNodeInfo(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - int num = responseContent.getInteger("activeConnectCount"); - logger.info("num" + i + ":" + num); - if (num >= 1) { - expect = true; - } - logger.info("temp" + i + ":" + temp); - logger.info("expect" + i + ":" + expect); - if (temp == true && expect == true) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(expect, temp); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount from solidity") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); - } - - @Test(enabled = true, description = "Json rpc api of net_version from solidity") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion from solidity") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3 from solidity") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL from solidity") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent from solidity") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity from solidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers from solidity") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount from solidity") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction from solidity") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign from solidity") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction from solidity") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork from solidity") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce from solidity") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate from solidity") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByHash params is false from solidity") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true from solidity") - public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("46blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); - logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); - - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong( - getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), - size); - - JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); - logger.info("transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java deleted file mode 100644 index c566fc5532c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - -@Slf4j -public class Accounts003 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; - - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { - - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() { - - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } - - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java deleted file mode 100644 index 6a1a67f00c4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ /dev/null @@ -1,388 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - -@Slf4j -public class Accounts004 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; - - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing from solidity.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_newFilter contains address,fromBlock and toBlock from solidity.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock from solidity.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic and address from solidity.") - public void test04GetNewFilterContainsTopicAndAddress() { - - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter only contain topic and blockHash from solidity.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter which only contains blockHash from solidity.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter check new and after block from solidity.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newBlockFilter from solidity") - public void test08GetEthNewBlockFilter() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_getFilterChanges has less 20 elements from solidity.") - public void test09GetFilterChanges() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_getLogs contains address ,fromBlock and toBlock from solidity.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } - - @Test( - enabled = true, - description = "Eth api of eth_getLogs both contains topic and address from solidity.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs from solidity.") - public void test12GetFilterLogsContainsAddress() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs from solidity.") - public void test13GetFilterLogsContainsTopic() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter from solidity" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element from solidity") - public void test15EthUninstallFilter() { - // create ID - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java deleted file mode 100644 index 0521f094147..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java +++ /dev/null @@ -1,121 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j - -public class BuildTransaction001 extends JsonRpcBase { - - JSONArray jsonRpcReceives = new JSONArray(); - //String txid; - private JSONObject responseContent; - private HttpResponse response; - String transactionString; - String transactionSignString; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - final String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - - @Test(enabled = true, description = "Json rpc api of buildTransaction for transfer trx") - public void test01JsonRpcApiTestOfBuildTransactionForTransferTrx() throws Exception { - final Long beforeRecevierBalance = HttpMethed.getBalance(httpFullNode, receiverAddress); - - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", ByteArray.toHexString(receiverAddress)); - param.addProperty("value", "0x1"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - transactionString = responseContent.getJSONObject("result").getString("transaction"); - transactionSignString = HttpMethed.gettransactionsign(httpFullNode, transactionString, - jsonRpcOwnerKey); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterRecevierBalance = HttpMethed.getBalance(httpFullNode, receiverAddress); - - Assert.assertEquals(afterRecevierBalance - beforeRecevierBalance,1L); - - } - - @Test(enabled = true, description = "Json rpc api of buildTransaction for transfer trc10") - public void test02JsonRpcApiTestOfBuildTransactionForTransferTrc10() throws Exception { - PublicMethed.waitProduceNextBlock(blockingStubFull); - final Long beforeTokenBalance = PublicMethed.getAssetBalanceByAssetId(ByteString - .copyFromUtf8(jsonRpcAssetId), receiverKey, blockingStubFull); - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", ByteArray.toHexString(receiverAddress)); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - transactionString = responseContent.getJSONObject("result").getString("transaction"); - transactionSignString = HttpMethed.gettransactionsign(httpFullNode, transactionString, - jsonRpcOwnerKey); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = PublicMethed.getAssetBalanceByAssetId(ByteString - .copyFromUtf8(jsonRpcAssetId), receiverKey, blockingStubFull); - - Assert.assertEquals(afterTokenBalance - beforeTokenBalance,1L); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java deleted file mode 100644 index 0fe564ad177..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java +++ /dev/null @@ -1,80 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - - -@Slf4j - -public class EthSmartContract001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test01JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals(dataResult,"0x000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000000000000000000000000000000000000000000000a546f6b65" - + "6e545243323000000000000000000000000000000000000000000000"); - } - - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test02JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals(dataResult,"0x147"); - } - - - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test03JsonRpcApiTestForEthGetCode() throws Exception { - JsonArray params = new JsonArray(); - params.add(trc20AddressHex); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertTrue(dataResult.length() > 1000L); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java deleted file mode 100644 index ee30990dd65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java +++ /dev/null @@ -1,69 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - - -@Slf4j - -public class GetBlock001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash") - public void test01JsonRpcApiTestForEthGetBlockByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockId); - params.add("true"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals(Integer.toHexString(blockNum), responseContent.getJSONObject("result") - .getString("number").substring(2)); - Assert.assertEquals(blockId, responseContent.getJSONObject("result").getString("hash") - .substring(2)); - Assert.assertTrue(responseContent.getJSONObject("result") - .getJSONArray("transactions").size() >= 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java deleted file mode 100644 index 7dc75caa32f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java +++ /dev/null @@ -1,343 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage001Address = ecKey1.getAddress(); - String linkage001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage001Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true, description = "Deploy contract with valid or invalid value") - public void deployContentValue() { - Assert.assertTrue(PublicMethed.sendcoin(linkage001Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Value is equal balance,this will be failed.Only use FreeNet,Other not change. - String filePath = "./src/test/resources/soliditycode/contractLinkage001.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String payableCode = retMap.get("byteCode").toString(); - String payableAbi = retMap.get("abI").toString(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account accountGet = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - Long accountBalance = accountGet.getBalance(); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, payableAbi, - payableCode, "", maxFeeLimit, accountBalance, 100, null, - linkage001Key, linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(fee == 0); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage001Address, 50000000L, - 0, 1, linkage001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - maxFeeLimit = maxFeeLimit - 50000000L; - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - //Value is 1,use BalanceGetEnergy,use FreeNet,fee==0. - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, payableAbi, payableCode, - "", maxFeeLimit, 1L, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Account infoafter1 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - - Assert.assertTrue(beforeBalance1 - fee1 - 1L == afterBalance1); - byte[] contractAddress = infoById1.get().getContractAddress().toByteArray(); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - Assert.assertTrue(account.getBalance() == 1L); - Assert.assertTrue(afterNetUsed1 == 0); - Assert.assertTrue(afterEnergyUsed1 > 0); - Assert.assertTrue(afterFreeNetUsed1 > 0); - - //Value is account all balance plus 1. balance is not sufficient,Nothing changde. - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - - account = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - Long valueBalance = account.getBalance(); - contractAddress = PublicMethed.deployContract(contractName, payableAbi, payableCode, "", - maxFeeLimit, valueBalance + 1, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(contractAddress == null); - Account infoafter2 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - Assert.assertTrue(afterNetUsed2 == 0); - Assert.assertTrue(afterEnergyUsed2 > 0); - Assert.assertTrue(afterFreeNetUsed2 > 0); - Assert.assertEquals(beforeBalance2, afterBalance2); - - //Value is account all balance.use freezeBalanceGetEnergy ,freezeBalanceGetNet .Balance ==0 - Assert.assertTrue(PublicMethed.freezeBalance(linkage001Address, 5000000L, - 0, linkage001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - account = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - valueBalance = account.getBalance(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, payableAbi, payableCode, - "", maxFeeLimit, valueBalance, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Account infoafter3 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - - Assert.assertTrue(afterNetUsed3 > 0); - Assert.assertTrue(afterEnergyUsed3 > 0); - Assert.assertTrue(afterFreeNetUsed3 > 0); - Assert.assertTrue(beforeBalance2 - fee == afterBalance2); - Assert.assertTrue(afterBalance3 == 0); - Assert.assertTrue(PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance() == valueBalance); - PublicMethed - .unFreezeBalance(linkage001Address, linkage001Key, 1, - linkage001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(linkage001Address, linkage001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java deleted file mode 100644 index 691ce5dadab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java +++ /dev/null @@ -1,345 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage005 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - Long zeroForCycleCost; - Long firstForCycleCost; - Long secondForCycleCost; - Long thirdForCycleCost; - Long forthForCycleCost; - Long fifthForCycleCost; - Long zeroForCycleTimes = 498L; - Long firstForCycleTimes = 500L; - Long secondForCycleTimes = 502L; - Long thirdForCycleTimes = 504L; - Long forthForCycleTimes = 506L; - Long fifthForCycleTimes = 508L; - byte[] contractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage005Address = ecKey1.getAddress(); - String linkage005Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage005Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Every same trigger use same energy and net") - public void testEnergyCostDetail() { - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.sendcoin(linkage005Address, 5000000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage005Address, 250000000000L, - 0, linkage005Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage005Address, 250000000000L, - 0, 1, linkage005Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage005.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 100, null, linkage005Key, - linkage005Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account infoafter = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("---------------:"); - long fee = infoById.get().getFee(); - - Assert.assertTrue(beforeBalance - fee == afterBalance); - //Assert.assertTrue(afterEnergyUsed > 0); - //Assert.assertTrue(afterFreeNetUsed > 0); - firstForCycleTimes = 1000L; - secondForCycleTimes = 1002L; - thirdForCycleTimes = 1004L; - - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", firstForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Account infoafter1 = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - firstForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - Assert.assertTrue((beforeBalance1 - fee) == afterBalance1); - Assert.assertTrue(afterEnergyUsed1 > beforeEnergyUsed1); - Assert.assertTrue(afterNetUsed1 > beforeNetUsed1); - //use EnergyUsed and NetUsed.balance not change - - String txid6 = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", secondForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - final String txid7 = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", thirdForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid6, blockingStubFull); - secondForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid7, blockingStubFull); - thirdForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - Assert.assertTrue(thirdForCycleCost - secondForCycleCost - == secondForCycleCost - firstForCycleCost); - - zeroForCycleTimes = 498L; - firstForCycleTimes = 500L; - secondForCycleTimes = 502L; - thirdForCycleTimes = 504L; - forthForCycleTimes = 506L; - fifthForCycleTimes = 508L; - AccountResourceMessage resourceInfo4 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info4 = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance4 = info4.getBalance(); - Long beforeEnergyLimit4 = resourceInfo4.getEnergyLimit(); - Long beforeEnergyUsed4 = resourceInfo4.getEnergyUsed(); - Long beforeFreeNetLimit4 = resourceInfo4.getFreeNetLimit(); - Long beforeNetLimit4 = resourceInfo4.getNetLimit(); - Long beforeNetUsed4 = resourceInfo4.getNetUsed(); - Long beforeFreeNetUsed4 = resourceInfo4.getFreeNetUsed(); - logger.info("beforeBalance4:" + beforeBalance4); - logger.info("beforeEnergyLimit4:" + beforeEnergyLimit4); - logger.info("beforeEnergyUsed4:" + beforeEnergyUsed4); - logger.info("beforeFreeNetLimit4:" + beforeFreeNetLimit4); - logger.info("beforeNetLimit4:" + beforeNetLimit4); - logger.info("beforeNetUsed4:" + beforeNetUsed4); - logger.info("beforeFreeNetUsed4:" + beforeFreeNetUsed4); - txid = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", zeroForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Account infoafter4 = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter4 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance4 = infoafter4.getBalance(); - Long afterEnergyLimit4 = resourceInfoafter4.getEnergyLimit(); - Long afterEnergyUsed4 = resourceInfoafter4.getEnergyUsed(); - Long afterFreeNetLimit4 = resourceInfoafter4.getFreeNetLimit(); - Long afterNetLimit4 = resourceInfoafter4.getNetLimit(); - Long afterNetUsed4 = resourceInfoafter4.getNetUsed(); - Long afterFreeNetUsed4 = resourceInfoafter4.getFreeNetUsed(); - logger.info("afterBalance4:" + afterBalance4); - logger.info("afterEnergyLimit4:" + afterEnergyLimit4); - logger.info("afterEnergyUsed4:" + afterEnergyUsed4); - logger.info("afterFreeNetLimit4:" + afterFreeNetLimit4); - logger.info("afterNetLimit4:" + afterNetLimit4); - logger.info("afterNetUsed4:" + afterNetUsed4); - logger.info("afterFreeNetUsed4:" + afterFreeNetUsed4); - logger.info("---------------:"); - Assert.assertTrue(beforeBalance4 - fee == afterBalance4); - Assert.assertTrue(afterEnergyUsed4 > beforeEnergyUsed4); - Assert.assertTrue(afterNetUsed4 > beforeNetUsed4); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - zeroForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", firstForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid2 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", secondForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid3 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", thirdForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid4 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", forthForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid5 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", fifthForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - firstForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - secondForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - thirdForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - forthForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid5, blockingStubFull); - fifthForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - Assert.assertTrue(thirdForCycleCost - secondForCycleCost - == secondForCycleCost - firstForCycleCost); - Assert.assertTrue(fifthForCycleCost - forthForCycleCost - == forthForCycleCost - thirdForCycleCost); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(linkage005Address, linkage005Key, 1, - linkage005Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage005Address, linkage005Key, 0, - linkage005Address, blockingStubFull); - PublicMethed.freedResource(linkage005Address, linkage005Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java deleted file mode 100644 index 74fde7b7fc6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java +++ /dev/null @@ -1,331 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage006 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - byte[] contractAddress; - String txid; - Optional infoById; - String initParmes; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage006Address = ecKey1.getAddress(); - String linkage006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] linkage006Address2 = ecKey2.getAddress(); - String linkage006Key2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage006Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Deploy contract with stack function") - public void teststackOutByContract() { - - Assert.assertTrue(PublicMethed.sendcoin(linkage006Address, 20000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage006Address, 1000000L, - 0, linkage006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage006Address, 1000000L, - 0, 1, linkage006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage006Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage006Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage006.sol"; - String contractName = "AA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //success ,balnace change.use EnergyUsed and NetUsed - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 1000L, 100, null, linkage006Key, - linkage006Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid is " + txid); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - Account infoafter = PublicMethed.queryAccount(linkage006Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage006Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue((beforeBalance - fee - 1000L) == afterBalance); - Assert.assertTrue((beforeNetUsed + netUsed) >= afterNetUsed); - Assert.assertTrue((beforeEnergyUsed + energyUsed) >= afterEnergyUsed); - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 1, - null, blockingStubFull); - } - - @Test(enabled = true, description = "Boundary value for contract stack(63 is the largest level)") - public void teststackOutByContract1() { - Assert.assertTrue(PublicMethed.sendcoin(linkage006Address2, 20000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage006Address2, 1000000L, - 0, linkage006Key2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage006Address2, 1000000L, - 0, 1, linkage006Key2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - //success ,balance change.use EnergyUsed and NetUsed - initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"63\""; - txid = PublicMethed.triggerContract(contractAddress, - "init(address,uint256)", initParmes, false, - 0, 100000000L, linkage006Address2, linkage006Key2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - Account infoafter1 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(linkage006Address2, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - Assert.assertTrue((beforeBalance1 - fee1) == afterBalance1); - Assert.assertTrue(afterNetUsed1 > beforeNetUsed1); - Assert.assertTrue((beforeEnergyUsed1 + energyUsed1) >= afterEnergyUsed1); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Boundary value for contract stack" - + "(Trigger 64 level can't success)") - public void teststackOutByContract2() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"64\""; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - //failed ,use EnergyUsed and NetUsed - txid = PublicMethed.triggerContract(contractAddress, - "init(address,uint256)", initParmes, false, - 1000, 100000000L, linkage006Address2, linkage006Key2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - - Account infoafter2 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue((beforeEnergyUsed2 + energyUsed2) >= afterEnergyUsed2); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 1, - linkage006Address2, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 1, - linkage006Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 0, - linkage006Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 1, - linkage006Address2, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 0, - linkage006Address2, blockingStubFull); - PublicMethed.freedResource(linkage006Address, linkage006Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(linkage006Address2, linkage006Key2, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java deleted file mode 100644 index fe16f92575c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java +++ /dev/null @@ -1,239 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract002Address = ecKey1.getAddress(); - String contract002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String txid; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true, description = "Deploy contract with java-tron support interface") - public void test01DeployTronNative() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract002Address = ecKey1.getAddress(); - String contract002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract002Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract002Address, 1000000L, - 0, 1, contract002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract002Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract002Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String contractName = "TronNative"; - String filePath = "./src/test/resources/soliditycode/contractScenario002.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract002Key, contract002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - logger.info(txid); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract002Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract002Address, blockingStubFull1) - .getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - logger.info("transaction fee is " + Long.toString(infoById.get().getFee())); - - Assert.assertTrue(energyUsage > 0); - Assert.assertTrue(balanceBefore == balanceAfter + infoById.get().getFee()); - PublicMethed.unFreezeBalance(contract002Address, contract002Key, 1, - contract002Address, blockingStubFull); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get smart contract with invalid address") - public void test02GetContractWithInvalidAddress() { - byte[] contractAddress = contract002Address; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - logger.info(smartContract.getAbi().toString()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from solidity") - public void test03GetTransactionByIdFromSolidity() { - Assert.assertFalse(PublicMethed.getTransactionById(txid, blockingStubSolidity) - .get().getSignature(0).isEmpty()); - Assert.assertEquals(PublicMethed.getTransactionById(txid, blockingStubFull), - PublicMethed.getTransactionById(txid, blockingStubSolidity)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT") - public void test04GetTransactionByIdFromPbft() { - Assert.assertFalse(PublicMethed.getTransactionById(txid, blockingStubPbft) - .get().getSignature(0).isEmpty()); - Assert.assertEquals(PublicMethed.getTransactionById(txid, blockingStubSoliInFull), - PublicMethed.getTransactionById(txid, blockingStubPbft)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from Solidity") - public void test05GetTransactionInfoByIdFromSolidity() throws Exception { - long netUsage = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getReceipt() - .getNetUsage(); - - Assert.assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubSolidity) - .get().getReceipt().getNetUsage(), netUsage); - - Assert - .assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubSoliInFull) - .get().getReceipt().getNetUsage(), netUsage); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT") - public void test06GetTransactionInfoByIdFromPbft() { - long energyUsage = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get() - .getReceipt() - .getEnergyUsage(); - - Assert.assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubPbft) - .get().getReceipt().getEnergyUsage(), energyUsage); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contract002Address, contract002Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java deleted file mode 100644 index c0630d1e6eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java +++ /dev/null @@ -1,511 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.springframework.util.StringUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - Integer consumeUserResourcePercent = 50; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(deployKey); - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.sendcoin(triggerAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Kitty Core\"") - public void deployErc721KittyCore() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(deployAddress, 100000000L, - 0, 1, deployKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.freezeBalance(deployAddress, 100000000L, 0, - deployKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.freezeBalance(triggerAddress, 100000000L, 0, - triggerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployAddress, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "KittyCore"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("Kitty Core"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(kittyCoreContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress).substring(2)); - - kittyCoreAddressAndCut = "000000000000000000000000" + ByteArray - .toHexString(kittyCoreContractAddress).substring(2); - kittyCoreAddressAndCut = kittyCoreAddressAndCut + "0000000000000000000000000000000000000000000" - + "000000000000000000100"; - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Sale Clock Auction\"") - public void deploySaleClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "SaleClockAuction"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("Sale Clock Auction"); - //saleClockAuctionContractAddress; - String data = "\"" + Base58.encode58Check(kittyCoreContractAddress) + "\"," + 100; - String deplTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address,uint256)", - data, "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, deployAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - - saleClockAuctionContractAddress = info.get().getContractAddress().toByteArray(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(saleClockAuctionContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - - String triggerTxid = PublicMethed - .triggerContract(saleClockAuctionContractAddress, "isSaleClockAuction()", "#", false, 0, - maxFeeLimit, deployAddress, deployKey, blockingStubFull); - Optional inFoByid = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Ttttt " + triggerTxid); - Assert.assertTrue(inFoByid.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Siring Clock Auction\"") - public void deploySiringClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "SiringClockAuction"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String data = "\"" + Base58.encode58Check(kittyCoreContractAddress) + "\"," + 100; - String siringClockAuctionContractAddressTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address,uint256)", - data, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info2 = PublicMethed - .getTransactionInfoById(siringClockAuctionContractAddressTxid, blockingStubFull); - siringClockAuctionContractAddress = info2.get().getContractAddress().toByteArray(); - Assert.assertTrue(info2.get().getResultValue() == 0); - SmartContract smartContract = PublicMethed.getContract(siringClockAuctionContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Gene Science Interface\"") - public void deployGeneScienceInterface() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "GeneScienceInterface"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, - 0L, consumeUserResourcePercent, null, deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - geneScienceInterfaceContractAddress = info2.get().getContractAddress().toByteArray(); - Assert.assertTrue(info2.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(geneScienceInterfaceContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - } - - @Test(enabled = true, description = "Set three contract address for Kitty Core, " - + "set three CXO roles") - public void triggerToSetThreeContractAddressToKittyCore() { - //Set SaleAuctionAddress to kitty core. - String saleContractString = "\"" + Base58.encode58Check(saleClockAuctionContractAddress) + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "setSaleAuctionAddress(address)", - saleContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(siringClockAuctionContractAddress) - + "\""; - txid = PublicMethed - .triggerContract(kittyCoreContractAddress, "setSiringAuctionAddress(address)", - siringContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Set gen contract to kitty core - String genContractString = "\"" + Base58.encode58Check(geneScienceInterfaceContractAddress) - + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setGeneScienceAddress(address)", genContractString, - false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Start the game. - Integer result = 1; - Integer times = 0; - while (result == 1) { - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "unpause()", "", false, 0, - 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - result = infoById.get().getResultValue(); - if (times++ == 3) { - break; - } - } - - Assert.assertTrue(result == 0); - logger.info("start the game " + txid); - - //Create one gen0 cat. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "-1000000000000000", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "gen0CreatedCount()", "#", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "getKitty(uint256)", "1", false, 0, 10000000, triggerAddress, - triggerKey, blockingStubFull); - logger.info("getKitty " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String newCxoAddress = "\"" + Base58.encode58Check(triggerAddress) - + "\""; - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("COO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CFO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, 1000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CEO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Create Gen0 cat") - public void triggerUseTriggerEnergyUsage() { - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] triggerUseTriggerEnergyUsageAddress = ecKey3.getAddress(); - final String triggerUseTriggerEnergyUsageKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(triggerUseTriggerEnergyUsageAddress, 100000000000L, - fromAddress, testKey002, blockingStubFull)); - String newCxoAddress = "\"" + Base58.encode58Check(triggerUseTriggerEnergyUsageAddress) - + "\""; - PublicMethed.waitProduceNextBlock(blockingStubFull); - final String txid1; - final String txid2; - final String txid3; - txid1 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("COO " + txid); - - txid2 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("CFO " + txid); - - txid3 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("CEO " + txid); - - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - infoById = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - infoById = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long beforeBalance = PublicMethed - .queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull).getBalance(); - logger.info("before balance is " + Long.toString(beforeBalance)); - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - logger.info("Q " + Long - .toString(infoById.get().getReceipt().getEnergyFee())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyFee() > 10000); - // Assert.assertTrue(infoById.get().getReceipt().getOriginEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() - == infoById.get().getReceipt().getEnergyFee() / 100 + infoById.get().getReceipt() - .getOriginEnergyUsage()); - - Long fee = infoById.get().getFee(); - Long afterBalance = PublicMethed - .queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull1).getBalance(); - logger.info("after balance is " + Long.toString(afterBalance)); - logger.info("fee is " + Long.toString(fee)); - Assert.assertTrue(beforeBalance == afterBalance + fee); - - logger.info("before EnergyUsage is " + infoById.get().getReceipt().getEnergyUsage()); - logger.info("before EnergyFee is " + infoById.get().getReceipt().getEnergyFee()); - logger.info("before OriginEnergyUsage is " + infoById.get().getReceipt() - .getOriginEnergyUsage()); - logger.info("before EnergyTotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue( - PublicMethed.freezeBalanceGetEnergy(triggerUseTriggerEnergyUsageAddress, 100000000L, - 0, 1, triggerUseTriggerEnergyUsageKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - beforeBalance = PublicMethed.queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull) - .getBalance(); - logger.info("before balance is " + Long.toString(beforeBalance)); - - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(triggerUseTriggerEnergyUsageAddress, blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - logger.info("before EnergyLimit is " + Long.toString(energyLimit)); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - logger.info("after EnergyUsage is " + infoById.get().getReceipt().getEnergyUsage()); - logger.info("after EnergyFee is " + infoById.get().getReceipt().getEnergyFee()); - logger.info("after OriginEnergyUsage is " + infoById.get().getReceipt().getOriginEnergyUsage()); - logger.info("after EnergyTotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - fee = infoById.get().getFee(); - afterBalance = PublicMethed.queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull1) - .getBalance(); - logger.info("after balance is " + Long.toString(afterBalance)); - logger.info("fee is " + Long.toString(fee)); - - accountResource = PublicMethed - .getAccountResource(triggerUseTriggerEnergyUsageAddress, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - - logger.info("after EnergyLimit is " + Long.toString(energyLimit)); - - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyFee() == 0); - - //Assert.assertTrue(infoById.get().getReceipt().getOriginEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() == infoById.get() - .getReceipt().getEnergyUsage() + infoById.get().getReceipt().getOriginEnergyUsage()); - // Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() == infoById.get() - // .getReceipt().getOriginEnergyUsage()); - - Assert.assertTrue(beforeBalance == afterBalance + fee); - PublicMethed.unFreezeBalance(deployAddress, deployKey, 1, - deployAddress, blockingStubFull); - PublicMethed.unFreezeBalance(triggerAddress, triggerKey, 1, - triggerAddress, blockingStubFull); - - PublicMethed - .unFreezeBalance(triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, 1, - triggerUseTriggerEnergyUsageAddress, blockingStubFull); - PublicMethed.freedResource(triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - fromAddress, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java deleted file mode 100644 index 7e11bc176dd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java +++ /dev/null @@ -1,231 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress1 = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - String txid = ""; - Optional infoById = null; - String contractName = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract014Address = ecKey1.getAddress(); - String contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String priKey014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Triple trigger in smart contract") - public void testTripleTrigger() { - - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(contract014Key); - PublicMethed.printAddress(receiverKey); - - Assert.assertTrue(PublicMethed.sendcoin(contract014Address, 50_000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceGetEnergy(contract014Address, 10_000_000_000L, 0, 1, priKey014, - blockingStubFull)); - - logger.info("contract014Address : == " + contract014Key); - //Deploy contract1, contract1 has a function to transaction 5 sun to target account - String contractName = "Contract1"; - String filePath = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, null, contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - //Deploy contract2, contract2 has a function to call contract1 transaction sun function. - // and has a revert function. - contractName = "contract2"; - String filePath1 = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String parame = "\"" + Base58.encode58Check(contractAddress1) + "\""; - - txid = PublicMethed.deployContractWithConstantParame(contractName, abi1, code1, - "constructor(address)", parame, "", maxFeeLimit, 1000000L, 100, null, - contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress2 = infoById.get().getContractAddress().toByteArray(); - - //Deploy contract3, trigger contrct2 function. - contractName = "contract3"; - String filePath2 = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - parame = "\"" + Base58.encode58Check(contractAddress2) + "\""; - - txid = PublicMethed.deployContractWithConstantParame(contractName, abi2, code2, - "constructor(address)", parame, "", maxFeeLimit, 1000000L, 100, null, - contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress3 = infoById.get().getContractAddress().toByteArray(); - - Assert.assertTrue(PublicMethed.sendcoin(receiverAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Test contract2 trigger contract1 to test call function - Account contract2AccountInfo = PublicMethed.queryAccount(contractAddress2, blockingStubFull); - final Long contract2BeforeBalance = contract2AccountInfo.getBalance(); - Account receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Long receiverBeforeBalance = receiverAccountInfo.getBalance(); - Account contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - Long contract1BeforeBalance = contract1AccountInfo.getBalance(); - logger.info("before contract1 balance is " + Long.toString(contract1BeforeBalance)); - logger.info("before receiver balance is " + Long.toString(receiverBeforeBalance)); - String receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "triggerContract1(address)", receiveAddress, false, - 0, maxFeeLimit, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contract2AccountInfo = PublicMethed.queryAccount(contractAddress2, blockingStubFull); - final Long contract2AfterBalance = contract2AccountInfo.getBalance(); - //contract2AccountInfo.getAccountResource().getFrozenBalanceForEnergy(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Long receiverAfterBalance = receiverAccountInfo.getBalance(); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - Long contract1AfterBalance = contract1AccountInfo.getBalance(); - logger.info("after contract1 balance is " + Long.toString(contract1AfterBalance)); - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 5); - Assert.assertTrue(contract2BeforeBalance - contract2AfterBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 5); - - //Test contract2 trigger contract1 but revert - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1BeforeBalance = contract1AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverBeforeBalance = receiverAccountInfo.getBalance(); - receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "triggerContract1ButRevert(address)", receiveAddress, false, - 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1AfterBalance = contract1AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverAfterBalance = receiverAccountInfo.getBalance(); - logger.info("after receiver balance is " + Long.toString(receiverAfterBalance)); - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 0); - - //Test contract3 trigger contract2 to call contract1 - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1BeforeBalance = contract1AccountInfo.getBalance(); - Account contract3AccountInfo = PublicMethed.queryAccount(contractAddress3, blockingStubFull); - final Long contract3BeforeBalance = contract3AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverBeforeBalance = receiverAccountInfo.getBalance(); - logger.info("before receiver balance is " + Long.toString(receiverBeforeBalance)); - logger.info("before contract3 balance is " + Long.toString(contract3BeforeBalance)); - receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress3, - "triggerContract2(address)", receiveAddress, false, - 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contract3AccountInfo = PublicMethed.queryAccount(contractAddress3, blockingStubFull); - final Long contract3AfterBalance = contract3AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverAfterBalance = receiverAccountInfo.getBalance(); - logger.info("after receiver balance is " + Long.toString(receiverAfterBalance)); - logger.info("after contract3 balance is " + Long.toString(contract3AfterBalance)); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1AfterBalance = contract1AccountInfo.getBalance(); - - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 5); - Assert.assertTrue(contract3BeforeBalance - contract3AfterBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 5); - - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(contract014Address, contract014Key, 1, contract014Address, - blockingStubFull); - PublicMethed.freedResource(contract014Address, contract014Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java deleted file mode 100644 index e937f957b67..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario015 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress1 = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - String txid = ""; - Optional infoById = null; - String contractName = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract014Address = ecKey1.getAddress(); - String contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "TRON TRC20 transfer token") - public void trc20Tron() { - ecKey1 = new ECKey(Utils.getRandom()); - contract014Address = ecKey1.getAddress(); - contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(contract014Key); - PublicMethed.printAddress(receiverKey); - - Assert.assertTrue(PublicMethed.sendcoin(contract014Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Deploy contract1, contract1 has a function to transaction 5 sun to target account - String contractName = "TRON TRC20"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_Scenario015_TRC20_TRON"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_Scenario015_TRC20_TRON"); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress1, "balanceOf(address)", siringContractString, - false, 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - logger.info(txid); - - siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\",\"" + 17 + "\""; - txid = PublicMethed.triggerContract(contractAddress1, "transfer(address,uint256)", - siringContractString, false, 0, 10000000L, contract014Address, - contract014Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress1, "balanceOf(address)", - siringContractString, false, 0, 10000000L, contract014Address, - contract014Key, blockingStubFull); - logger.info(txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contract014Address, contract014Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java deleted file mode 100644 index d6786d6695a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java +++ /dev/null @@ -1,696 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.dailybuild.exceptionfee.AssertException; - -@Slf4j -public class ContractTrc1155 { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private final String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - Optional infoById = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] ownerAddressByte = ecKey2.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String ownerAddressString = null; - String holderAddressString = null; - String noHolderAddress = null; - String txid = null; - byte[] trc1155AddressByte = null; - /** constructor. */ - - @BeforeSuite - public void beforeSuite() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - deployTrc1155(); - - deployHolder(); - deployNoHolder(); - } - - @Test(enabled = true, description = "Trigger Trc1155 balanceOf method") - public void test01triggerTrc1155BalanceOfMethod() { - int coinType = 3; - List parameters = Arrays.asList(ownerAddressString, coinType); - String data = PublicMethed.parametersString(parameters); - - logger.info("data:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4), result); - } - - @Test(enabled = true, description = "Trigger Trc1155 balanceOfBatch method") - public void test02triggerTrc1155BalanceOfBatchMethod() { - List address = - Stream.of( - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString) - .collect(Collectors.toList()); - List coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - List parameters = Arrays.asList(address, coinType); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - GrpcAPI.TransactionExtention transactionExtention1 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention1.getConstantResult(0).toByteArray()); - logger.info("hexBalance:" + hexBalance); - final long trxAmount = (long) Math.pow(10, 3); - final long bttAmount = (long) Math.pow(10, 2); - final long winAmount = (long) Math.pow(10, 5); - final long sunAmount = (long) Math.pow(10, 4); - final long apenftAmount = 1L; - final long apenft1Amount = 1L; - Assert.assertEquals(trxAmount, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(bttAmount, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals(winAmount, Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals(sunAmount, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(apenftAmount, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(apenft1Amount, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Trigger Trc1155 safeTransferFrom function") - public void test03triggerTrc1155SafeTransferFromFunction() { - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contract003Address = ecKey3.getAddress(); - String sendAddress = WalletClient.encode58Check(contract003Address); - logger.info(sendAddress); - int coinType = 3; - final int coinAmount = 2; - List parameters1 = Arrays.asList(ownerAddressString, coinType); - String data = PublicMethed.parametersString(parameters1); - logger.info("data1:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4), result); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters = - Arrays.asList(ownerAddressString, sendAddress, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - String txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - - List parameters3 = Arrays.asList(ownerAddressString, coinType); - data = PublicMethed.parametersString(parameters3); - logger.info("data3:" + data); - GrpcAPI.TransactionExtention transactionExtention3 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention3.getConstantResult(0).toByteArray()); - result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4) - coinAmount, result); - - parameters = Arrays.asList(sendAddress, coinType); - data = PublicMethed.parametersString(parameters); - - logger.info("data2:" + data); - transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(coinAmount, result); - } - - @Test(enabled = true, description = "trigger Trc1155 SafeBatchTransferFrom function") - public void test04triggerTrc1155SafeBatchTransferFromFunction() { - - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey4.getAddress(); - String sendAddress = WalletClient.encode58Check(receiverAddress); - List coinType = Stream.of(0, 1, 5).collect(Collectors.toList()); - List coinAccount = Stream.of(50, 10, 1).collect(Collectors.toList()); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters = - Arrays.asList(ownerAddressString, sendAddress, coinType, coinAccount, bytes); - String input = PublicMethed.parametersString(parameters); - logger.info("input:" + input); - String txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)", - input, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - List address = - Stream.of( - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString) - .collect(Collectors.toList()); - List coinType1 = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - List parameters1 = Arrays.asList(address, coinType1); - String data = PublicMethed.parametersString(parameters1); - - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("hexBalance:" + hexBalance); - Assert.assertEquals( - (long) Math.pow(10, 3) - 50, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals( - (long) Math.pow(10, 2) - 10, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals((long) Math.pow(10, 5), Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals( - (long) Math.pow(10, 4) - 2, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(0, Long.parseLong(hexBalance.substring(448, 512), 16)); - - address = - Stream.of( - sendAddress, - sendAddress, - ownerAddressString, - ownerAddressString, - ownerAddressString, - sendAddress) - .collect(Collectors.toList()); - coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - parameters = Arrays.asList(address, coinType); - data = PublicMethed.parametersString(parameters); - - logger.info("data2:" + data); - transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(50, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(10, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals((long) Math.pow(10, 5), Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals( - (long) Math.pow(10, 4) - 2, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Trc1155Holder can receive trc1155") - public void test05Trc1155HolderCanReceiveTrc1155() { - List parameters = Arrays.asList(holderAddressString, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - int coinType = 0; - int coinAmount = 10; - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - parameters = - Arrays.asList(ownerAddressString, holderAddressString, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - logger.info("infobyid1 : --- " + byId); - - logger.info("infobyid1 : --- " + infoById); - - parameters = Arrays.asList(holderAddressString, coinType); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(coinAmount, result); - } - - @Test(enabled = true, description = "Trc1155Holder can receive trc1155[]") - public void test06Trc1155HolderCanReceiveTrc1155_01() { - - List parameters = Arrays.asList(holderAddressString, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - int trxAmount = 50; - int bttAmount = 30; - int winAmount = 25; - int sunAmount = 10; - int apenftAmount = 1; - List coinType = Stream.of(0, 1, 2, 3, 4).collect(Collectors.toList()); - List coinAmount = - Stream.of(trxAmount, bttAmount, winAmount, sunAmount, apenftAmount) - .collect(Collectors.toList()); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - parameters = - Arrays.asList(ownerAddressString, holderAddressString, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data1:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeBatchTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid1 : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - List address = - Stream.of( - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString) - .collect(Collectors.toList()); - coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - parameters = Arrays.asList(address, coinType); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(trxAmount + 10, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(bttAmount, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals(winAmount, Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals(sunAmount, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(apenftAmount, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(0, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Non-trc1155Holder can not receive trc1155") - public void test07NonTrc1155HolderCanNotReceiveTrc1155() { - List parameters = Arrays.asList(noHolderAddress, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters1 = Arrays.asList(ownerAddressString, noHolderAddress, 1, 1, bytes); - String data1 = PublicMethed.parametersString(parameters1); - logger.info("data:" + data1); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data1, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid1 : --- " + infoById); - parameters = Arrays.asList(noHolderAddress, 1); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention1 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention1.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(0, result); - } - - /** constructor. */ - public void deployTrc1155() throws Exception { - Assert.assertTrue( - PublicMethed.sendcoin( - ownerAddressByte, 500000000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "TronCoins"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - int deploySuccessFlag = 1; - Integer retryTimes = 5; - - while (retryTimes-- > 0 && deploySuccessFlag != 0) { - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - logger.info("smartContract:" + smartContract); - trc1155AddressByte = contractAddress.toByteArray(); - ownerAddressString = WalletClient.encode58Check(ownerAddressByte); - logger.info("trc1155AddressByte:" + trc1155AddressByte); - logger.info("ownerAddressString:" + ownerAddressString); - deploySuccessFlag = infoById.get().getResult().getNumber(); - } - - Assert.assertEquals(deploySuccessFlag, 0); - } - - /** constructor. */ - public void deployHolder() throws Exception { - String contractName = "MyContractCanReceiver"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - - holderAddressString = WalletClient.encode58Check(contractAddress.toByteArray()); - - logger.info("HolderAddress:" + holderAddressString); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertEquals(infoById.get().getResult().getNumber(), 0); - } - - /** constructor. */ - public void deployNoHolder() throws Exception { - String contractName = "MyContractCanNotReceiver"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - - noHolderAddress = WalletClient.encode58Check(contractAddress.toByteArray()); - logger.info("NoHolderAddress:" + noHolderAddress); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertEquals(infoById.get().getResult().getNumber(), 0); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(fromAddress, ownerKey, ownerAddressByte, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java deleted file mode 100644 index 17fa1ef3f4a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java +++ /dev/null @@ -1,343 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractUnknownException { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] grammarAddress2 = ecKey2.getAddress(); - String testKeyForGrammarAddress2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey3.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] grammarAddress4 = ecKey4.getAddress(); - String testKeyForGrammarAddress4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "trigger selfdestruct method") - public void testGrammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress, 204800000, - 0, 1, testKeyForGrammarAddress, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final String s = infoById.get().getResMessage().toStringUtf8(); - long fee = infoById.get().getFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - Account infoafter = PublicMethed.queryAccount(grammarAddress, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - PublicMethed.unFreezeBalance(grammarAddress, testKeyForGrammarAddress, 1, grammarAddress, - blockingStubFull); - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "trigger revert method") - public void testGrammar002() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress2, 100000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress2, 10000000L, - 0, 1, testKeyForGrammarAddress2, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress2, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress2, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final long fee = infoById.get().getFee(); - final long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - - final String s = infoById.get().getResMessage().toStringUtf8(); - - Account infoafter = PublicMethed.queryAccount(grammarAddress2, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress2, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertFalse(energyFee == 1000000000); - - Assert.assertTrue(beforeBalance - fee == afterBalance); - PublicMethed.unFreezeBalance(grammarAddress2, testKeyForGrammarAddress2, 1, grammarAddress2, - blockingStubFull); - PublicMethed.freedResource(grammarAddress2, testKeyForGrammarAddress2, testNetAccountAddress, - blockingStubFull); - - } - - @Test(enabled = true, description = "trigger assert method") - public void testGrammar003() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress3, 1000000000L, - 0, 1, testKeyForGrammarAddress3, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress3, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress3, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final long fee = infoById.get().getFee(); - final long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - String s = infoById.get().getResMessage().toStringUtf8(); - Account infoafter = PublicMethed.queryAccount(grammarAddress3, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress3, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - logger.info("s:" + s); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertTrue(beforeBalance - fee == afterBalance); - PublicMethed.unFreezeBalance(grammarAddress3, testKeyForGrammarAddress3, 1, grammarAddress3, - blockingStubFull); - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - - } - - - @Test(enabled = true, description = "trigger require method") - public void testGrammar004() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress4, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress4, 100000000L, - 0, 1, testKeyForGrammarAddress4, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress4, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress4, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testD"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress4, - grammarAddress4, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final String s = infoById.get().getResMessage().toStringUtf8(); - final long fee = infoById.get().getFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - - Account infoafter = PublicMethed.queryAccount(grammarAddress4, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress4, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertTrue(beforeBalance - fee == afterBalance); - Assert.assertFalse(energyFee == 1000000000); - PublicMethed.unFreezeBalance(grammarAddress4, testKeyForGrammarAddress4, 1, grammarAddress4, - blockingStubFull); - PublicMethed.freedResource(grammarAddress4, testKeyForGrammarAddress4, testNetAccountAddress, - blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java deleted file mode 100644 index 459d96c5cec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java +++ /dev/null @@ -1,53 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import org.junit.Assert; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class GetTransactionInfoByBlockNumFromSolidity { - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public String fullNode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - public String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - - @Test(enabled = true, description = "test getTransactionInfoByBlockNumFromSolidity") - public void test01GetTransactionInfoByBlockNumFromSolidity() { - channelFull = ManagedChannelBuilder.forTarget(fullNode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(solidityNode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Protocol.Block solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - long block = solidityCurrentBlock.getBlockHeader().getRawData().getNumber(); - long targetBlock; - for (targetBlock = block; targetBlock > 0; targetBlock--) { - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(targetBlock); - if (blockingStubSolidity.getTransactionCountByBlockNum(builder.build()).getNum() > 0) { - break; - } - } - - GrpcAPI.TransactionInfoList transactionList = - PublicMethed.getTransactionInfoByBlockNum(targetBlock, blockingStubFull).get(); - - GrpcAPI.TransactionInfoList transactionListFromSolidity = - PublicMethed.getTransactionInfoByBlockNum(targetBlock, blockingStubFull).get(); - Assert.assertEquals(transactionList, transactionListFromSolidity); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java deleted file mode 100644 index 7070ab0db33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class RateLimite001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub realBlockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode) - .usePlaintext(true) - .build(); - realBlockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListWitness interface") - public void test1QpsStrategyForListWitnessInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 20) { - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListNodes interface") - public void test2IpQpsStrategyForListNodesInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 20) { - blockingStubFull.listNodes(EmptyMessage.newBuilder().build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for getBlockByNum2 " - + "interface on fullnode's solidity service") - public void test3IpQpsStrategyForgetBlockByNum2ResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - - while (repeatTimes++ < 20) { - blockingStubSolidity.getBlockByNum2(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit QpsStrategy for getBlockByNum " - + "interface on fullnode's solidity service") - public void test4QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - while (repeatTimes++ < 20) { - blockingStubSolidity.getBlockByNum(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for getBlockByNum2 " - + "interface on real solidity") - public void test5IpQpsStrategyForgetBlockByNum2ResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - - while (repeatTimes++ < 20) { - realBlockingStubSolidity.getBlockByNum2(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit QpsStrategy for getBlockByNum " - + "interface on real solidity") - public void test6QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - while (repeatTimes++ < 20) { - realBlockingStubSolidity.getBlockByNum(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java deleted file mode 100644 index ce5ec3bfaf3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java +++ /dev/null @@ -1,791 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class RequireException { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelFull2 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull2 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue016); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Require Exception") - public void test1TestRequireContract() { - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - - Assert.assertTrue(PublicMethed - .sendcoin(asset016Address, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = - "src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testRequire()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Throw Exception") - public void test2TestThrowsContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testThrow()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testTestThrowsContract"); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - - @Test(enabled = true, description = "Call Revert ") - public void test3TestRevertContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testRevert()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = false, description = "No payable function call value") - public void test4noPayableContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol"; - String contractName = "noPayableContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "noPayable()", "#", false, - 22, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = false, description = "No payable Constructor") - public void test5noPayableConstructor() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String filePath = - "src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol"; - String contractName = "MyContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 22L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "Transfer failed") - public void test6transferTestContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol"; - String contractName = "transferTestContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - final Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String newCxoAddress = "\"" + Base58.encode58Check(testNetAccountAddress) - + "\""; - final String txid = PublicMethed.triggerContract(contractAddress, - "tranferTest(address) ", newCxoAddress, false, - 5, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("transferTestContract"); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "No payable fallback call value") - public void test7payableFallbakContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Integer times = 0; - String contractName1 = "Test"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1; - contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, 0L, - 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - final String txid = PublicMethed.triggerContract(contractAddress1, - "callTest(address)", saleContractString, false, - 5, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "New contract gas not enough") - public void test8newContractGasNoenough() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol"; - String contractName = "Account"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "Initialize"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "newAccount()", "#", false, - 0, 5226000, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "Message used error") - public void test9MessageUsedErrorFeed() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol"; - String contractName = "MathedFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - String contractName1 = "MathedUseContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "messageUse(address)", saleContractString, false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Function used error") - public void testFunctionUsedErrorFeed() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol"; - String contractName = "MessageFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - - String contractName1 = "MessageUseContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, 0L, - 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "messageUse(address)", saleContractString, false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - PublicMethed.freedResource(asset016Address, testKeyForAssetIssue016, testNetAccountAddress, - blockingStubFull); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java deleted file mode 100644 index cdf1adfd022..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java +++ /dev/null @@ -1,163 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /* @Test(enabled = true) - public void TestGetAllAccount(){ - GrpcAPI.AccountList accountlist = - blockingStubFull.listAccounts(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(accountlist); - if (result.isPresent()) { - GrpcAPI.AccountList accountList = result.get(); - List list = accountList.getAccountsList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new AccountComparator()); - GrpcAPI.AccountList.Builder builder = GrpcAPI.AccountList.newBuilder(); - newList.forEach(account -> builder.addAccounts(account)); - result = Optional.of(builder.build()); - } - Assert.assertTrue(result.get().getAccountsCount() > 0); - logger.info(Integer.toString(result.get().getAccountsCount())); - for (int j = 0; j < result.get().getAccountsCount(); j++){ - Assert.assertFalse(result.get().getAccounts(j).getAddress().isEmpty()); - } - - - }*/ - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java deleted file mode 100644 index c9437546cda..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java +++ /dev/null @@ -1,128 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount010 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account010Address = ecKey1.getAddress(); - String account010Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account010SecondAddress = ecKey2.getAddress(); - String account010SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] account010InvalidAddress = ecKey3.getAddress(); - String account010InvalidKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(account010Key); - PublicMethed.printAddress(account010SecondKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = false) - public void testGetStorage() { - Assert.assertTrue(PublicMethed.sendcoin(account010Address, 100000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account010SecondAddress, 100000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account010InvalidAddress, 100000000, - fromAddress, testKey002, blockingStubFull)); - Account account010Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account010Info.getAccountResource().getStorageLimit() == 0); - Assert.assertTrue(account010Info.getAccountResource().getLatestExchangeStorageTime() == 0); - - Assert.assertTrue(PublicMethed.buyStorage(100000000L, account010Address, account010Key, - blockingStubFull)); - - account010Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account010Info.getAccountResource().getStorageLimit() > 0); - Assert.assertTrue(account010Info.getAccountResource().getLatestExchangeStorageTime() > 0); - - AccountResourceMessage account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - Assert.assertTrue(account010Resource.getStorageLimit() > 0); - } - - @Test(enabled = false) - public void testSellStorage() { - AccountResourceMessage account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - Long storageLimit = account010Resource.getStorageLimit(); - Account account001Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account001Info.getBalance() == 0); - //When there is no enough storage,sell failed. - Assert.assertFalse(PublicMethed.sellStorage(storageLimit + 1, account010Address, account010Key, - blockingStubFull)); - //Can not sell 0 storage - Assert.assertFalse(PublicMethed.sellStorage(0, account010Address, account010Key, - blockingStubFull)); - //Sell all storage. - Assert.assertTrue(PublicMethed.sellStorage(storageLimit, account010Address, account010Key, - blockingStubFull)); - account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - storageLimit = account010Resource.getStorageLimit(); - Assert.assertTrue(storageLimit == 0); - account001Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account001Info.getBalance() > 0); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java deleted file mode 100644 index f4aa3b2d523..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java +++ /dev/null @@ -1,188 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key25"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key2"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - //get account - - /** - * constructor. - */ - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - @Test(enabled = false, threadPoolSize = 20, invocationCount = 20) - public void storageAndCpu() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset011Address = ecKey1.getAddress(); - String testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAssetIssue011); - - PublicMethed - .sendcoin(asset011Address, 100000000000000L, fromAddress, testKey002, blockingStubFull); - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_WalletTestAccount012_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_WalletTestAccount012_storageAndCpu"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue011, asset011Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - String txid; - - Integer i = 1; - AccountResourceMessage accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - Long beforeEnergyLimit = accountResource.getEnergyLimit(); - Long afterEnergyLimit; - Long beforeTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - Account account = PublicMethed.queryAccount(testKeyForAssetIssue011, blockingStubFull); - Long afterTotalEnergyLimit; - while (i++ < 20000) { - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - beforeEnergyLimit = accountResource.getEnergyLimit(); - beforeTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - String initParmes = "\"" + "21" + "\""; - /* txid = PublicMethed.triggerContract(contractAddress, - "storage8Char()", "", false, - 0, maxFeeLimit, asset011Address, testKeyForAssetIssue011, blockingStubFull);*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - txid = PublicMethed.triggerContract(contractAddress, - "add2(uint256)", initParmes, false, - 0, maxFeeLimit, asset011Address, testKeyForAssetIssue011, blockingStubFull); - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - //logger.info("Current limit is " + accountResource.getTotalEnergyLimit()); - //PublicMethed.freezeBalanceGetEnergy(asset011Address,1000000L,3, - // 1,testKeyForAssetIssue011,blockingStubFull); - - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - afterEnergyLimit = accountResource.getEnergyLimit(); - afterTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - - logger.info("Total energy limit is " + (float) afterTotalEnergyLimit / 50000000000L); - Float rate = - (float) (afterTotalEnergyLimit - beforeTotalEnergyLimit) / beforeTotalEnergyLimit; - //logger.info("rate is " + rate); - //Assert.assertTrue(rate >= 0.001001000 && rate <= 0.001001002); - //txidList.add(txid); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - account = PublicMethed.queryAccount(testKeyForAssetIssue011, blockingStubFull); - Float energyrate = (float) (beforeEnergyLimit) / account.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance(); - //logger.info("energy rate is " + energyrate); - if (i % 20 == 0) { - PublicMethed.freezeBalanceForReceiver(fromAddress, 1000000L, 3, 1, - ByteString.copyFrom(asset011Address), testKey002, blockingStubFull); - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java deleted file mode 100644 index e6d94b64fed..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java +++ /dev/null @@ -1,515 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional infoById = null; - long account013BeforeBalance; - long freezeAmount = 10000000L; - long freezeDuration = 0; - byte[] account013Address; - String testKeyForAccount013; - byte[] receiverDelegateAddress; - String receiverDelegateKey; - byte[] emptyAddress; - String emptyKey; - byte[] account4DelegatedResourceAddress; - String account4DelegatedResourceKey; - byte[] account5DelegatedResourceAddress; - String account5DelegatedResourceKey; - byte[] accountForDeployAddress; - String accountForDeployKey; - byte[] accountForAssetIssueAddress; - String accountForAssetIssueKey; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Delegate resource for bandwidth and energy") - public void test1DelegateResourceForBandwidthAndEnergy() { - //Create account013 - ECKey ecKey1 = new ECKey(Utils.getRandom()); - account013Address = ecKey1.getAddress(); - testKeyForAccount013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAccount013); - //Create receiver - ECKey ecKey2 = new ECKey(Utils.getRandom()); - receiverDelegateAddress = ecKey2.getAddress(); - receiverDelegateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(receiverDelegateKey); - //Create Empty account - ECKey ecKey3 = new ECKey(Utils.getRandom()); - emptyAddress = ecKey3.getAddress(); - emptyKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - //sendcoin to Account013 - Assert.assertTrue(PublicMethed - .sendcoin(account013Address, 10000000000L, fromAddress, testKey002, blockingStubFull)); - //sendcoin to receiver - Assert.assertTrue(PublicMethed - .sendcoin(receiverDelegateAddress, 10000000000L, toAddress, testKey003, blockingStubFull)); - - //getAccountResource account013 - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage account013Resource = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - logger.info("013 energy limit is " + account013Resource.getEnergyLimit()); - logger.info("013 net limit is " + account013Resource.getNetLimit()); - //getAccountResource receiver - AccountResourceMessage receiverResource = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - logger.info("receiver energy limit is " + receiverResource.getEnergyLimit()); - logger.info("receiver net limit is " + receiverResource.getNetLimit()); - Protocol.Account account013infoBefore = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //get resources of account013 before DelegateResource - account013BeforeBalance = account013infoBefore.getBalance(); - AccountResourceMessage account013ResBefore = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - final long account013BeforeBandWidth = account013ResBefore.getNetLimit(); - AccountResourceMessage receiverResourceBefore = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - long receiverBeforeBandWidth = receiverResourceBefore.getNetLimit(); - //Account013 DelegateResource for BandWidth to receiver - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(receiverDelegateAddress), testKeyForAccount013, blockingStubFull)); - Protocol.Account account013infoAfter = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //get balance of account013 after DelegateResource - long account013AfterBalance = account013infoAfter.getBalance(); - AccountResourceMessage account013ResAfter = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - //get BandWidth of account013 after DelegateResource - long account013AfterBandWidth = account013ResAfter.getNetLimit(); - AccountResourceMessage receiverResourceAfter = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Bandwidth of receiver after DelegateResource - long receiverAfterBandWidth = receiverResourceAfter.getNetLimit(); - //Balance of Account013 reduced amount same as DelegateResource - Assert.assertTrue(account013BeforeBalance == account013AfterBalance + freezeAmount); - //Bandwidth of account013 is equally before and after DelegateResource - Assert.assertTrue(account013AfterBandWidth == account013BeforeBandWidth); - //Bandwidth of receiver after DelegateResource is greater than before - Assert.assertTrue(receiverAfterBandWidth > receiverBeforeBandWidth); - Protocol.Account account013Before1 = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //balance of account013 before DelegateResource - long account013BeforeBalance1 = account013Before1.getBalance(); - AccountResourceMessage account013ResBefore1 = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - //Energy of account013 before DelegateResource - long account013BeforeEnergy = account013ResBefore1.getEnergyLimit(); - AccountResourceMessage receiverResourceBefore1 = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Energy of receiver before DelegateResource - long receiverBeforeEnergy = receiverResourceBefore1.getEnergyLimit(); - //Account013 DelegateResource Energy to receiver - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(receiverDelegateAddress), testKeyForAccount013, blockingStubFull)); - Protocol.Account account013infoAfter1 = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //balance of account013 after DelegateResource - long account013AfterBalance1 = account013infoAfter1.getBalance(); - AccountResourceMessage account013ResAfter1 = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - long account013AfterEnergy = account013ResAfter1.getEnergyLimit(); - //Energy of account013 after DelegateResource - AccountResourceMessage receiverResourceAfter1 = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Energy of receiver after DelegateResource - long receiverAfterEnergy = receiverResourceAfter1.getEnergyLimit(); - //Balance of Account013 reduced amount same as DelegateResource - Assert.assertTrue(account013BeforeBalance1 == account013AfterBalance1 + freezeAmount); - //Bandwidth of account013 is equally before and after DelegateResource - Assert.assertTrue(account013AfterEnergy == account013BeforeEnergy); - //Bandwidth of receiver after DelegateResource is greater than before - Assert.assertTrue(receiverAfterEnergy > receiverBeforeEnergy); - //account013 DelegateResource to Empty failed - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(emptyAddress), testKeyForAccount013, blockingStubFull)); - //account013 DelegateResource to account013 failed - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(account013Address), testKeyForAccount013, blockingStubFull)); - account013Resource = PublicMethed.getAccountResource(account013Address, blockingStubFull); - logger.info("After 013 energy limit is " + account013Resource.getEnergyLimit()); - logger.info("After 013 net limit is " + account013Resource.getNetLimit()); - - receiverResource = PublicMethed.getAccountResource(receiverDelegateAddress, blockingStubFull); - logger.info("After receiver energy limit is " + receiverResource.getEnergyLimit()); - logger.info("After receiver net limit is " + receiverResource.getNetLimit()); - } - - @Test(enabled = true, description = "Get delegate resource") - public void test2getDelegatedResource() { - //Create Account4 - ECKey ecKey4 = new ECKey(Utils.getRandom()); - account4DelegatedResourceAddress = ecKey4.getAddress(); - account4DelegatedResourceKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - //Create Account5 - ECKey ecKey5 = new ECKey(Utils.getRandom()); - account5DelegatedResourceAddress = ecKey5.getAddress(); - account5DelegatedResourceKey = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - //sendcoin to Account4 - Assert.assertTrue(PublicMethed - .sendcoin(account4DelegatedResourceAddress, 10000000000L, fromAddress, testKey002, - blockingStubFull)); - - //sendcoin to Account5 - Assert.assertTrue(PublicMethed - .sendcoin(account5DelegatedResourceAddress, 20000000000L, toAddress, testKey003, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Protocol.Account account4infoBefore = PublicMethed - .queryAccount(account4DelegatedResourceAddress, blockingStubFull); - //Balance of Account4 before DelegateResource - final long account4BeforeBalance = account4infoBefore.getBalance(); - //account013 DelegateResource of bandwidth to Account4 - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(account4DelegatedResourceAddress), testKeyForAccount013, - blockingStubFull)); - //Account4 DelegateResource of energy to Account5 - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account4DelegatedResourceAddress, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(account5DelegatedResourceAddress), account4DelegatedResourceKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //check DelegatedResourceList,from:account013 to:Account4 - Optional delegatedResourceResult1 = PublicMethed - .getDelegatedResource(account013Address, account4DelegatedResourceAddress, - blockingStubFull); - long afterFreezeBandwidth = delegatedResourceResult1.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth(); - //check DelegatedResourceList,from:Account4 to:Account5 - Optional delegatedResourceResult2 = PublicMethed - .getDelegatedResource(account4DelegatedResourceAddress, account5DelegatedResourceAddress, - blockingStubFull); - long afterFreezeEnergy = delegatedResourceResult2.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy(); - //FrozenBalanceForBandwidth > 0 - Assert.assertTrue(afterFreezeBandwidth > 0); - //FrozenBalanceForEnergy > 0 - Assert.assertTrue(afterFreezeEnergy > 0); - - //check DelegatedResourceAccountIndex for Account4 - Optional delegatedResourceIndexResult1 = PublicMethed - .getDelegatedResourceAccountIndex(account4DelegatedResourceAddress, blockingStubFull); - //result of From list, first Address is same as account013 address - Assert.assertTrue(new String(account013Address) - .equals(new String(delegatedResourceIndexResult1.get().getFromAccounts(0).toByteArray()))); - //result of To list, first Address is same as Account5 address - Assert.assertTrue(new String(account5DelegatedResourceAddress) - .equals(new String(delegatedResourceIndexResult1.get().getToAccounts(0).toByteArray()))); - - //unfreezebalance of bandwidth from Account013 to Account4 - Assert.assertTrue(PublicMethed.unFreezeBalance(account013Address, testKeyForAccount013, 0, - account4DelegatedResourceAddress, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //check DelegatedResourceAccountIndex of Account4 - Optional delegatedResourceIndexResult1AfterUnfreeze = - PublicMethed - .getDelegatedResourceAccountIndex(account4DelegatedResourceAddress, blockingStubFull); - //result of From list is empty - Assert.assertTrue( - delegatedResourceIndexResult1AfterUnfreeze.get().getFromAccountsList().isEmpty()); - Assert.assertFalse( - delegatedResourceIndexResult1AfterUnfreeze.get().getToAccountsList().isEmpty()); - //Balance of Account013 after unfreezeBalance - // (013 -> receiver(bandwidth), 013 -> receiver(Energy), 013 -> Account4(bandwidth)) - Assert.assertTrue(PublicMethed.queryAccount(account013Address, blockingStubFull).getBalance() - == account013BeforeBalance - 2 * freezeAmount); - //bandwidth from Account013 to Account4 gone - Assert.assertTrue( - PublicMethed.getAccountResource(account4DelegatedResourceAddress, blockingStubFull) - .getNetLimit() == 0); - - //unfreezebalance of Energy from Account4 to Account5 - Assert.assertTrue(PublicMethed - .unFreezeBalance(account4DelegatedResourceAddress, account4DelegatedResourceKey, 1, - account5DelegatedResourceAddress, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account account4infoAfterUnfreezeEnergy = PublicMethed - .queryAccount(account4DelegatedResourceAddress, blockingStubFull); - //balance of Account4 after unfreezebalance - long account4BalanceAfterUnfreezeEnergy = account4infoAfterUnfreezeEnergy.getBalance(); - //balance of Account4 is same as before - Assert.assertTrue(account4BeforeBalance == account4BalanceAfterUnfreezeEnergy); - //Energy from Account4 to Account5 gone - Assert.assertTrue( - PublicMethed.getAccountResource(account5DelegatedResourceAddress, blockingStubFull) - .getEnergyLimit() == 0); - - //Unfreezebalance of Bandwidth from Account4 to Account5 fail - Assert.assertFalse(PublicMethed - .unFreezeBalance(account4DelegatedResourceAddress, account4DelegatedResourceKey, 0, - account5DelegatedResourceAddress, blockingStubFull)); - } - - @Test(enabled = true, description = "Prepare delegate resource token") - public void test3PrepareToken() { - //Create Account7 - ECKey ecKey7 = new ECKey(Utils.getRandom()); - accountForAssetIssueAddress = ecKey7.getAddress(); - accountForAssetIssueKey = ByteArray.toHexString(ecKey7.getPrivKeyBytes()); - //sendcoin to Account7 - Assert.assertTrue(PublicMethed - .sendcoin(accountForAssetIssueAddress, 10000000000L, toAddress, testKey003, - blockingStubFull)); - //account013 DelegateResource of bandwidth to accountForAssetIssue - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, 1000000000L, freezeDuration, 0, - ByteString.copyFrom(accountForAssetIssueAddress), testKeyForAccount013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //accountForAssetIssue AssetIssue - long now = System.currentTimeMillis(); - String name = "testAccount013_" + Long.toString(now); - long totalSupply = 100000000000L; - String description = "zfbnb"; - String url = "aaa.com"; - Assert.assertTrue(PublicMethed - .createAssetIssue(accountForAssetIssueAddress, name, totalSupply, 1, 1, - System.currentTimeMillis() + 2000, System.currentTimeMillis() + 1000000000, 1, - description, url, 2000L, 2000L, 500L, 1L, accountForAssetIssueKey, blockingStubFull)); - - } - - @Test(enabled = true, description = "Delegate resource about transfer asset") - public void test4DelegateResourceAboutTransferAsset() { - //Wait for 3s - PublicMethed.waitProduceNextBlock(blockingStubFull); - //get AssetIssue Id - Protocol.Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed - .queryAccount(accountForAssetIssueAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - //Account5 Participate AssetIssue - Assert.assertTrue(PublicMethed - .participateAssetIssue(accountForAssetIssueAddress, assetAccountId.toByteArray(), 1000000, - account5DelegatedResourceAddress, account5DelegatedResourceKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //get account013,accountForAssetIssue,Account5 account resources before transferAssets - final long account013CurrentBandwidth = PublicMethed - .getAccountResource(account013Address, blockingStubFull).getNetUsed(); - long accountForAssetIssueCurrentBandwidth = PublicMethed - .getAccountResource(accountForAssetIssueAddress, blockingStubFull).getNetUsed(); - final long account5CurrentBandwidth = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull).getNetUsed(); - //Account5 transfer Assets receiver - Assert.assertTrue(PublicMethed - .transferAsset(receiverDelegateAddress, assetAccountId.toByteArray(), 100000, - account5DelegatedResourceAddress, account5DelegatedResourceKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(accountForAssetIssueKey); - PublicMethed.printAddress(account5DelegatedResourceKey); - - //get account013,accountForAssetIssue,Account5 resource after transferAsset - final long account013CurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(account013Address, blockingStubFull).getNetUsed(); - final long accountForAssetIssueCurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(accountForAssetIssueAddress, blockingStubFull).getFreeNetUsed(); - final long account5CurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull).getNetUsed(); - AccountResourceMessage account5ResourceAfterTrans = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull); - - String result = ""; - if (account5ResourceAfterTrans.getAssetNetLimitCount() > 0) { - logger.info("getAssetNetLimitCount > 0 "); - for (String name1 : account5ResourceAfterTrans.getAssetNetLimitMap().keySet()) { - logger.info(name1); - result += account5ResourceAfterTrans.getAssetNetUsedMap().get(name1); - - } - } - logger.info(result); - PublicMethed.printAddress(receiverDelegateKey); - PublicMethed.printAddress(account5DelegatedResourceKey); - long account5FreeAssetNetUsed = accountForAssetIssueCurrentBandwidthAfterTrans; - - //check resource diff - Assert.assertTrue(Long.parseLong(result) > 0); - Assert.assertTrue(account013CurrentBandwidth == account013CurrentBandwidthAfterTrans); - Assert.assertTrue(account5CurrentBandwidth == account5CurrentBandwidthAfterTrans); - } - - @Test(enabled = true, description = "Can't delegate resource for contract") - public void test5CanNotDelegateResourceToContract() { - //Create Account6 - ECKey ecKey6 = new ECKey(Utils.getRandom()); - accountForDeployAddress = ecKey6.getAddress(); - accountForDeployKey = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - //PublicMethed.printAddress(accountForDeployKey); - //sendcoin to Account6 - Assert.assertTrue(PublicMethed - .sendcoin(accountForDeployAddress, 10000000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //deploy contract under Account6 - Integer consumeUserResourcePercent = 0; - Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - String contractName = "TestSStore"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_WalletTestAccount013"); - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_WalletTestAccount013"); - - logger.info("TestSStore"); - final byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, consumeUserResourcePercent, - null, accountForDeployKey, accountForDeployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Account4 DelegatedResource of Energy to Contract - //After 3.6 can not delegate resource to contract - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account4DelegatedResourceAddress, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(contractAddress), account4DelegatedResourceKey, blockingStubFull)); - } - - - @Test(enabled = true, description = "Get delegate resource from solidity") - public void test6GetDelegateResourceFromSolidity() { - Optional delegateResource = PublicMethed - .getDelegatedResourceFromSolidity(account013Address, receiverDelegateAddress, - blockingStubSolidity); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy() == 10000000); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth() == 10000000); - } - - @Test(enabled = true, description = "Get delegate resource from PBFT") - public void test7GetDelegateResourceFromPbft() { - Optional delegateResource = PublicMethed - .getDelegatedResourceFromSolidity(account013Address, receiverDelegateAddress, - blockingStubPbft); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy() == 10000000); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth() == 10000000); - } - - @Test(enabled = true, description = "Get delegate resource index from solidity") - public void test8GetDelegateResourceIndexFromSolidity() { - Optional delegateResourceIndex = PublicMethed - .getDelegatedResourceAccountIndexFromSolidity(account013Address, - blockingStubSolidity); - Assert.assertTrue(delegateResourceIndex.get().getToAccountsCount() == 2); - } - - @Test(enabled = true, description = "Get delegate resource index from PBFT") - public void test9GetDelegateResourceIndexFromPbft() { - Optional delegateResourceIndex = PublicMethed - .getDelegatedResourceAccountIndexFromSolidity(account013Address, - blockingStubSolidity); - Assert.assertTrue(delegateResourceIndex.get().getToAccountsCount() == 2); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account013Address, testKeyForAccount013, - fromAddress, blockingStubFull); - PublicMethed.freedResource(receiverDelegateAddress, receiverDelegateKey, fromAddress, - blockingStubFull); - PublicMethed.freedResource(account4DelegatedResourceAddress, account4DelegatedResourceKey, - fromAddress, blockingStubFull); - PublicMethed.freedResource(account5DelegatedResourceAddress, account5DelegatedResourceKey, - fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java deleted file mode 100644 index 2dbf04b380b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account014Address = ecKey1.getAddress(); - String account014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account014SecondAddress = ecKey2.getAddress(); - String account014SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - } - - @Test(enabled = true, description = "Query freeNetUsage in 50061") - public void fullAndSoliMerged1ForFreeNetUsage() { - //Create account014 - ecKey1 = new ECKey(Utils.getRandom()); - account014Address = ecKey1.getAddress(); - account014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ecKey2 = new ECKey(Utils.getRandom()); - account014SecondAddress = ecKey2.getAddress(); - account014SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(account014Key); - PublicMethed.printAddress(account014SecondKey); - Assert.assertTrue(PublicMethed.sendcoin(account014Address, 1000000000L, fromAddress, - testKey002, blockingStubFull)); - - //Test freeNetUsage in fullnode and soliditynode. - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 5000000L, - account014Address, account014Key, - blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 5000000L, - account014Address, account014Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account account014 = PublicMethed.queryAccount(account014Address, blockingStubFull); - final long freeNetUsageInFullnode = account014.getFreeNetUsage(); - final long createTimeInFullnode = account014.getCreateTime(); - final long lastOperationTimeInFullnode = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInFullnode = account014.getLatestConsumeFreeTime(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSoliInFull); - final long freeNetUsageInSoliInFull = account014.getFreeNetUsage(); - final long createTimeInSoliInFull = account014.getCreateTime(); - final long lastOperationTimeInSoliInFull = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInSoliInFull = account014.getLatestConsumeFreeTime(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSolidity); - final long freeNetUsageInSolidity = account014.getFreeNetUsage(); - final long createTimeInSolidity = account014.getCreateTime(); - final long lastOperationTimeInSolidity = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInSolidity = account014.getLatestConsumeFreeTime(); - Assert.assertTrue(freeNetUsageInSoliInFull > 0 && freeNetUsageInSolidity > 0 - && freeNetUsageInFullnode > 0); - Assert.assertTrue(freeNetUsageInFullnode <= freeNetUsageInSoliInFull + 5 - && freeNetUsageInFullnode >= freeNetUsageInSoliInFull - 5); - Assert.assertTrue(freeNetUsageInFullnode <= freeNetUsageInSolidity + 5 - && freeNetUsageInFullnode >= freeNetUsageInSolidity - 5); - Assert.assertTrue(createTimeInFullnode == createTimeInSolidity && createTimeInFullnode - == createTimeInSoliInFull); - Assert.assertTrue(createTimeInSoliInFull != 0); - Assert.assertTrue(lastOperationTimeInFullnode == lastOperationTimeInSolidity - && lastOperationTimeInFullnode == lastOperationTimeInSoliInFull); - Assert.assertTrue(lastOperationTimeInSoliInFull != 0); - Assert.assertTrue(lastCustomeFreeTimeInFullnode == lastCustomeFreeTimeInSolidity - && lastCustomeFreeTimeInFullnode == lastCustomeFreeTimeInSoliInFull); - Assert.assertTrue(lastCustomeFreeTimeInSoliInFull != 0); - } - - @Test(enabled = true, description = "Query net usage in 50061") - public void fullAndSoliMerged2ForNetUsage() { - - Assert.assertTrue(PublicMethed.freezeBalance(account014Address, 1000000L, 3, - account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 1000000L, - account014Address, account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account014Address, 1000000, - 3, 1, account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014Address, 1000000, - 3, 0, ByteString.copyFrom( - account014SecondAddress), account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014Address, 1000000, - 3, 1, ByteString.copyFrom( - account014SecondAddress), account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014SecondAddress, 1000000, - 3, 0, ByteString.copyFrom( - account014Address), account014SecondKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014SecondAddress, 1000000, - 3, 1, ByteString.copyFrom( - account014Address), account014SecondKey, blockingStubFull)); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - Account account014 = PublicMethed.queryAccount(account014Address, blockingStubFull); - final long lastCustomeTimeInFullnode = account014.getLatestConsumeTime(); - final long netUsageInFullnode = account014.getNetUsage(); - final long acquiredForBandwidthInFullnode = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInFullnode = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInFullnode = account014 - .getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInFullnode = account014 - .getAccountResource().getDelegatedFrozenBalanceForEnergy(); - logger.info("delegatedForEnergyInFullnode " + delegatedForEnergyInFullnode); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSoliInFull); - final long lastCustomeTimeInSoliInFull = account014.getLatestConsumeTime(); - logger.info("freeNetUsageInSoliInFull " + lastCustomeTimeInSoliInFull); - final long netUsageInSoliInFull = account014.getNetUsage(); - final long acquiredForBandwidthInSoliInFull = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInSoliInFull = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInSoliInFull = account014 - .getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInSoliInFull = account014 - .getAccountResource().getDelegatedFrozenBalanceForEnergy(); - logger.info("delegatedForEnergyInSoliInFull " + delegatedForEnergyInSoliInFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSolidity); - final long netUsageInSolidity = account014.getNetUsage(); - final long lastCustomeTimeInSolidity = account014.getLatestConsumeTime(); - final long acquiredForBandwidthInSolidity = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInSolidity = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInSolidity = account014.getAccountResource() - .getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInSolidity = account014.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(); - - logger.info("delegatedForEnergyInSolidity " + delegatedForEnergyInSolidity); - Assert.assertTrue(netUsageInSoliInFull > 0 && netUsageInSolidity > 0 - && netUsageInFullnode > 0); - Assert.assertTrue(netUsageInFullnode <= netUsageInSoliInFull + 5 - && netUsageInFullnode >= netUsageInSoliInFull - 5); - Assert.assertTrue(netUsageInFullnode <= netUsageInSolidity + 5 - && netUsageInFullnode >= netUsageInSolidity - 5); - Assert.assertTrue(acquiredForBandwidthInFullnode == acquiredForBandwidthInSoliInFull - && acquiredForBandwidthInFullnode == acquiredForBandwidthInSolidity); - Assert.assertTrue(delegatedBandwidthInFullnode == delegatedBandwidthInSoliInFull - && delegatedBandwidthInFullnode == delegatedBandwidthInSolidity); - Assert.assertTrue(acquiredForEnergyInFullnode == acquiredForEnergyInSoliInFull - && acquiredForEnergyInFullnode == acquiredForEnergyInSolidity); - Assert.assertTrue(delegatedForEnergyInFullnode == delegatedForEnergyInSoliInFull - && delegatedForEnergyInFullnode == delegatedForEnergyInSolidity); - Assert.assertTrue(acquiredForBandwidthInSoliInFull == 1000000 - && delegatedBandwidthInSoliInFull == 1000000 && acquiredForEnergyInSoliInFull == 1000000 - && delegatedForEnergyInSoliInFull == 1000000); - logger.info("lastCustomeTimeInSoliInFull " + lastCustomeTimeInSoliInFull); - Assert.assertTrue(lastCustomeTimeInFullnode == lastCustomeTimeInSolidity - && lastCustomeTimeInFullnode == lastCustomeTimeInSoliInFull); - logger.info("lastCustomeTimeInSoliInFull " + lastCustomeTimeInSoliInFull); - Assert.assertTrue(lastCustomeTimeInSoliInFull != 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account014Address, account014Key, fromAddress, blockingStubFull); - PublicMethed - .freedResource(account014SecondAddress, account014SecondKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java deleted file mode 100644 index 640f6f202ad..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount015 { - - private static final long now = System.currentTimeMillis(); - private static long amount = 100000000L; - private static String accountId = "accountid_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account015Address = ecKey1.getAddress(); - String account015Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - Random rand = new Random(); - amount = amount + rand.nextInt(10000); - } - - @Test(enabled = true, description = "Set account id") - public void test01SetAccountId() { - //Create account014 - ecKey1 = new ECKey(Utils.getRandom()); - account015Address = ecKey1.getAddress(); - account015Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - PublicMethed.printAddress(account015Key); - Assert.assertTrue(PublicMethed.sendcoin(account015Address, amount, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.setAccountId(accountId.getBytes(), - account015Address, account015Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get account by id") - public void test02GetAccountById() { - Assert.assertEquals(amount, PublicMethed.getAccountById( - accountId, blockingStubFull).getBalance()); - } - - - @Test(enabled = true, description = "Get account by id from solidity") - public void test03GetAccountByIdFromSolidity() { - Assert.assertEquals(amount, PublicMethed.getAccountByIdFromSolidity( - accountId, blockingStubSoliInFull).getBalance()); - } - - @Test(enabled = true, description = "Get account by id from PBFT") - public void test04GetAccountByIdFromPbft() { - Assert.assertEquals(amount, PublicMethed.getAccountByIdFromSolidity( - accountId, blockingStubPbft).getBalance()); - } - - - @Test(enabled = true, description = "Get account from PBFT") - public void test05GetAccountFromPbft() { - Assert.assertEquals(amount, PublicMethed.queryAccount( - account015Address, blockingStubPbft).getBalance()); - } - - - @Test(enabled = true, description = "List witnesses") - public void test06ListWitness() { - Assert.assertTrue(PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesCount() >= 2); - } - - @Test(enabled = true, description = "List witnesses from solidity node") - public void test07ListWitnessFromSolidity() { - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubSolidity) - .get().getWitnessesCount() >= 2); - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubSoliInFull) - .get().getWitnessesCount() >= 2); - } - - @Test(enabled = true, description = "List witnesses from PBFT node") - public void test08ListWitnessFromPbft() { - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubPbft) - .get().getWitnessesCount() >= 2); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account015Address, account015Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java deleted file mode 100644 index e38dc2065eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class WalletTestBlock001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from fullnode") - public void testCurrentBlock() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock is " + Long.toString(currentBlock.getBlockHeader() - .getRawData().getNumber())); - - //Improve coverage. - currentBlock.equals(currentBlock); - Block newBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - newBlock.equals(currentBlock); - newBlock.hashCode(); - newBlock.getSerializedSize(); - newBlock.getTransactionsCount(); - newBlock.getTransactionsList(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from solidity") - public void testCurrentBlockFromSolidity() { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock in soliditynode is " + Long.toString(currentBlock - .getBlockHeader().getRawData().getNumber())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java deleted file mode 100644 index 3517f4696cd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java +++ /dev/null @@ -1,381 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestBlock002 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByNum from fullnode") - public void test01GetBlockByNum() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubFull.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubFull.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubFull.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - } - - @Test(enabled = true, description = "GetBlockByNum from solidity") - public void test02GetBlockByNumFromSolidity() { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubSolidity.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubSolidity.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubSolidity.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - } - - @Test(enabled = true, description = "Get block by id") - public void test03GetBlockById() { - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - ByteString currentHash = currentBlock.getBlockHeader().getRawData().getParentHash(); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(currentHash).build(); - Block setIdOfBlock = blockingStubFull.getBlockById(request); - Assert.assertTrue(setIdOfBlock.hasBlockHeader()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - logger.info(Long.toString(setIdOfBlock.getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - setIdOfBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlock.getBlockHeader() - .getRawData().getNumber()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("By ID test succesfully"); - } - - - @Test(enabled = true, description = "Get transaction count by block num") - public void test04GetTransactionCountByBlockNum() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubFull.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get transaction count by block num from solidity") - public void test05GetTransactionCountByBlockNumFromSolidity() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubSolidity.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - Assert.assertTrue(blockingStubSoliInFull.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get transaction count by block num from PBFT") - public void test06GetTransactionCountByBlockNumFromPbft() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubPbft.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get now block from PBFT") - public void test07GetNowBlockFromPbft() { - Block nowBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nowBlockNum = nowBlock.getBlockHeader().getRawData().getNumber(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubPbft); - Block pbftNowBlock = blockingStubPbft.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nowPbftBlockNum = pbftNowBlock.getBlockHeader().getRawData().getNumber(); - logger.info("nowBlockNum:" + nowBlockNum + " , nowPbftBlockNum:" + nowPbftBlockNum); - Assert.assertTrue(nowPbftBlockNum >= nowBlockNum); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubPbft); - GrpcAPI.BlockExtention pbftNowBlock2 = blockingStubPbft.getNowBlock2(GrpcAPI.EmptyMessage - .newBuilder().build()); - Long nowPbftBlockNum2 = pbftNowBlock2.getBlockHeader().getRawData().getNumber(); - logger.info("nowBlockNum:" + nowBlockNum + " , nowPbftBlockNum2:" + nowPbftBlockNum2); - Assert.assertTrue(nowPbftBlockNum2 >= nowBlockNum); - } - - - @Test(enabled = true, description = "Get block by num from PBFT") - public void test08GetBlockByNumFromPbft() { - Block currentBlock = blockingStubPbft - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubPbft.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubPbft.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubPbft.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - - //Query the second latest block getBlockByNum2. - NumberMessage.Builder builder4 = NumberMessage.newBuilder(); - builder4.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock1 = blockingStubPbft.getBlockByNum2(builder4.build()); - Assert.assertTrue(lastSecondBlock1.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock1.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getRawData().getWitnessAddress() - .isEmpty()); - Assert.assertTrue( - lastSecondBlock1.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock1.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from getBlockByNum2 succesfully"); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java deleted file mode 100644 index 7b69b3b11b6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java +++ /dev/null @@ -1,459 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = updateAccountPermissionFee + multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - @Test(enabled = true, description = "List exchange after create exchange by MutiSign") - public void test3ListExchange() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - for (Integer i = 0; i < listExchange.get().getExchangesCount(); i++) { - Assert.assertFalse(ByteArray.toHexString(listExchange.get().getExchanges(i) - .getCreatorAddress().toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getExchangeId() > 0); - Assert.assertFalse(ByteArray.toStr(listExchange.get().getExchanges(i).getFirstTokenId() - .toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getFirstTokenBalance() > 0); - } - } - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "GetExchangeListPaginated after " - + "MutiSign exchange kind of transaction") - - public void test7GetExchangeListPaginated() { - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(100); - ExchangeList exchangeList = blockingStubFull - .getPaginatedExchangeList(pageMessageBuilder.build()); - Assert.assertTrue(exchangeList.getExchangesCount() >= 1); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - //Solidity support getExchangeId - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity); - logger.info("createtime is" + exchangeIdInfo.get().getCreateTime()); - Assert.assertTrue(exchangeIdInfo.get().getCreateTime() > 0); - - //Solidity support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubSolidity); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, exchange001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .unFreezeBalance(exchange001Address, exchange001Key, 0, fromAddress, blockingStubFull); - PublicMethed.freedResource(exchange001Address, exchange001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(secondExchange001Address, secondExchange001Key, fromAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java deleted file mode 100644 index e9496dc9a7d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java +++ /dev/null @@ -1,106 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestNode001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - - @Test(enabled = true, description = "List all nodes") - public void testGetAllNode() { - GrpcAPI.NodeList nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.NodeList nodeList1 = blockingStubFull1 - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer times = 0; - while (nodeList.getNodesCount() == 0 && times++ < 5) { - nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - nodeList1 = blockingStubFull1 - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - if (nodeList.getNodesCount() != 0 || nodeList1.getNodesCount() != 0) { - break; - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - //Assert.assertTrue(nodeList.getNodesCount() != 0 || nodeList1.getNodesCount() != 0); - - for (Integer j = 0; j < nodeList.getNodesCount(); j++) { - //Assert.assertTrue(nodeList.getNodes(j).hasAddress()); - //Assert.assertFalse(nodeList.getNodes(j).getAddress().getHost().isEmpty()); - //Assert.assertTrue(nodeList.getNodes(j).getAddress().getPort() < 65535); - //logger.info(ByteArray.toStr(nodeList.getNodes(j).getAddress().getHost().toByteArray())); - } - logger.info("get listnode succesuflly"); - - //Improve coverage. - GrpcAPI.NodeList newNodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - nodeList.equals(nodeList); - nodeList.equals(newNodeList); - nodeList.getNodesList(); - nodeList.hashCode(); - nodeList.isInitialized(); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java deleted file mode 100644 index 06760b8f94d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java +++ /dev/null @@ -1,208 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.TransferContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestTransfer002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false) - public void testGetTotalTransaction() { - NumberMessage beforeGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(beforeGetTotalTransaction.getNum())); - Long beforeTotalTransaction = beforeGetTotalTransaction.getNum(); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - NumberMessage afterGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(afterGetTotalTransaction.getNum())); - Long afterTotalTransaction = afterGetTotalTransaction.getNum(); - Assert.assertTrue(afterTotalTransaction - beforeTotalTransaction > 0); - - //Improve coverage. - afterGetTotalTransaction.equals(beforeGetTotalTransaction); - afterGetTotalTransaction.equals(afterGetTotalTransaction); - afterGetTotalTransaction.hashCode(); - afterGetTotalTransaction.isInitialized(); - afterGetTotalTransaction.getSerializedSize(); - afterGetTotalTransaction.getDefaultInstanceForType(); - afterGetTotalTransaction.getParserForType(); - afterGetTotalTransaction.getUnknownFields(); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java deleted file mode 100644 index 39c8ad9daef..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java +++ /dev/null @@ -1,227 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer005 { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = false) - public void testgetTransactionsFromThis() { - //Create a transfer. - //Assert.assertTrue(PublicMethed.sendcoin(toAddress,1000000,fromAddress, - // testKey002,blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - Optional gettransactionsfromthis = Optional - .ofNullable(transactionList); - - if (gettransactionsfromthis.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - } - - Assert.assertTrue(gettransactionsfromthis.isPresent()); - Integer beforecount = gettransactionsfromthis.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse(gettransactionsfromthis.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsFromThisByInvaildAddress() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - Optional gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java deleted file mode 100644 index 4223cdafca6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer006 { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = false) - public void testgetTransactionsToThis() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(toAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - - Optional gettransactionstothis = Optional - .ofNullable(transactionList); - - if (gettransactionstothis.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - //logger.info("This account didn't transfation any coin to other"); - } - - Assert.assertTrue(gettransactionstothis.isPresent()); - Integer beforecount = gettransactionstothis.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse(gettransactionstothis.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsToThisByInvaildAddress() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - Optional gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java deleted file mode 100644 index f76efdfd6ed..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java +++ /dev/null @@ -1,326 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestWitness003 { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 9999000000L; - private static final String tooLongUrl = "qagwqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String testUpdateWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] updateAddress = PublicMethed.getFinalAddress(testUpdateWitnessKey); - String createWitnessUrl = "http://www.createwitnessurl.com"; - String updateWitnessUrl = "http://www.updatewitnessurl.com"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Invaild account to apply create witness") - public void testInvaildToApplyBecomeWitness() { - Assert.assertFalse(createWitnessNotBroadcast(INVAILD_ADDRESS, createUrl, testKey002)); - } - - @Test(enabled = true, description = "Create witness") - public void testCreateWitness() { - //If you are already is witness, apply failed - //createWitness(fromAddress, createUrl, testKey002); - //Assert.assertFalse(createWitness(fromAddress, createUrl, testKey002)); - - //No balance,try to create witness. - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, createUrl, lowBalTest)); - - //Send enough coin to the apply account to make that account - // has ability to apply become witness. - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - GrpcAPI.WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - Assert.assertTrue(PublicMethed - .sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002, - blockingStubFull)); - //null url, update failed - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, wrongUrl, testUpdateWitnessKey)); - //too long url, update failed - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, - tooLongUrl.getBytes(), testUpdateWitnessKey)); - Assert.assertTrue(createWitnessNotBroadcast(lowBalAddress, createUrl, lowBalTest)); - - } - } - - @Test(enabled = true, description = "Update witness") - public void testUpdateWitness() { - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - GrpcAPI.WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - //null url, update failed - Assert.assertFalse(updateWitness(updateAddress, wrongUrl, testUpdateWitnessKey)); - //too long url, update failed - Assert.assertFalse(updateWitness(updateAddress, tooLongUrl.getBytes(), testUpdateWitnessKey)); - //Content space and special char, update success - Assert.assertTrue(updateWitness(updateAddress, updateSpaceUrl, testUpdateWitnessKey)); - //update success - Assert.assertTrue(updateWitness(updateAddress, updateUrl, testUpdateWitnessKey)); - } else { - logger.info("Update witness case had been test.This time skip it."); - } - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitnessNotBroadcast(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessCreateContract.Builder builder = WitnessCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - return true; - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessUpdateContract.Builder builder = WitnessUpdateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = PublicMethed.broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java deleted file mode 100644 index eb9f64b1073..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java +++ /dev/null @@ -1,894 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign01 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner permission_name is owner") - public void testOwnerName01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is owner1") - public void testOwnerName02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner1\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is string \"123\"") - public void testOwnerName03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"123\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is string \"\"") - public void testOwnerName04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is null") - public void testOwnerName05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - // null - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":" + null - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner without permission_name") - public void testOwnerName06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is numbers") - public void testOwnerName07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":123,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is 0.1") - public void testOwnerName08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"0.1\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name length is 32") - public void testOwnerName09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Owner permission_name length is 33") - public void testOwnerName10() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner permission_name contains special char") - public void testOwnerName11() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"0&^%\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0&^%%09\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - logger.info("1111___" + PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getOwnerPermission().toString()); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("22222___" + PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getOwnerPermission().toString()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java deleted file mode 100644 index b732a0e1619..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java +++ /dev/null @@ -1,719 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign02 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner threshold in exception condition") - public void testOwnerThreshold01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":-2147483648," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":0," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":-1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - logger.info("** update owner and active permission to two address"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036855775828,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036854775809,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":\"12a\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":\"\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":" + null + ",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = 1.1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 1.1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = Long.MAX_VALUE < sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner threshold is 1") - public void testOwnerThreshold02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner threshold is more than sum of keys' weight") - public void testOwnerThreshold03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // theshold = Long.MAX_VALUE > sum(weight) - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":214748364}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not" - + " be less than threshold in permission Owner", - response.getMessage().toStringUtf8()); - - // theshold = Integer.MAX_VALUE > sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":214748364}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight " - + "should not be less than threshold in permission Owner", - response.getMessage().toStringUtf8()); - - // theshold = Long.MAX_VALUE + 1 > sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner threshold is Long.MAX_VALUE and equal sum(weight)") - public void testOwnerThreshold04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner threshold is Integer.MAX_VALUE") - public void testOwnerThreshold05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java deleted file mode 100644 index cb0817fb70b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java +++ /dev/null @@ -1,541 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign03 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner doesn't have parent_id") - public void testOwnerParent01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner parent_id in exception condition") - public void testOwnerParent02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"123\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"abc\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":" + null + ",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":1,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":3,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":3,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2147483647,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2147483648,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":-2147483648,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":-2147483649,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner parent_id is 0") - public void testOwnerParent03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":0,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java deleted file mode 100644 index abb64dc6274..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java +++ /dev/null @@ -1,550 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign04 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner weight in exception condition") - public void testOwnerWeight01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":0}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":0}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036854775808}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036855775828}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"12a\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":" + null + "}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // sum(weight) > Long.MAX_VALUE - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - // weight = 1.1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1.1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner weight is 1") - public void testOwnerWeight02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - - @Test(enabled = true, description = "Owner weight is Long.MAX_VALUE") - public void testOwnerWeight04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java deleted file mode 100644 index b4c639089cc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java +++ /dev/null @@ -1,746 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign05 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner key-address is witness account") - public void testOwnerKeyAddress01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner key-address is contract address") - public void testOwnerKeyAddress02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address is inactive address") - public void testOwnerKeyAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey01); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address is owner address") - public void testOwnerKeyAddress04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner key-address in exception condition") - public void testOwnerKeyAddress05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = owner_address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : address should be distinct " - + "in permission Owner", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress - + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, fakeAddress.getBytes(), ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = "1.1" - fakeAddress = "1.1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress - + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner key-address count is 5") - public void testOwnerKeyAddress06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(5, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(testKey002); - ownerPermissionKeys.add(witnessKey001); - ownerPermissionKeys.add(tmpKey01); - ownerPermissionKeys.add(tmpKey02); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address count in exception condition") - public void testOwnerKeyAddress07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address count = 6 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : number of keys in permission should" - + " not be greater than 5", - response.getMessage().toStringUtf8()); - - // address count = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5," - + "\"keys\":[]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java deleted file mode 100644 index f5c58d5b7b0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java +++ /dev/null @@ -1,689 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign06 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner type in exception condition") - public void testOwnerType01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - // type = 1 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":2,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036855775828,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":\"12a\",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: For input string: \"12a\""); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":\"\",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - accountPermissionJson = - "{\"owner_permission\":{\"type\":,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":" + null + ",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - // type = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":2147483647,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":9223372036854775807,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036854775809,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 10 - accountPermissionJson = "{\"owner_permission\":{\"type\":9223372036854775817," - + "\"permission_name\":\"owner\",\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner type is 0") - public void testOwnerType02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner type is Long.Min") - public void testOwnerType03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036854775808,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner type is Long.MAX_VALUE + 1") - public void testOwnerType04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":9223372036854775808,\"permission_name\":\"Owner\"," - + "\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner type is 0.1") - public void testOwnerType05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0.1," - + "\"permission_name\":\"owner\",\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java deleted file mode 100644 index 41745b6047b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java +++ /dev/null @@ -1,662 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign07 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner permission_name is owner") - public void testActiveName01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"owner\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - @Test(enabled = true, description = "Owner permission_name is active") - public void testActiveName02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - @Test(enabled = true, description = "Owner permission_name is activea") - public void testActiveName03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"activea\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name is \"123\"") - public void testActiveName04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"123\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name is \"\"") - public void testActiveName05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name in exception condition") - public void testActiveName06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" + null - + ",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // name = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":,\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("Expected com.alibaba.fastjson.JSONException!"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner permission_name is 1.1") - public void testActiveName07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":1.1,\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission_name length is 32") - public void testActiveName08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1000000, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Active permission_name length is 33") - public void testActiveName09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner001\",\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java deleted file mode 100644 index e23d5d7d6ca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java +++ /dev/null @@ -1,623 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign08 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active threshold is exception condition") - public void testActiveTheshold01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.Min_Value - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-2147483648," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":0," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036854775808," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036855775828," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036854775809," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":\"-12a\"," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException : -12a !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":\"\"," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":" + null + "," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = 1.9 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1.9," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":21}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - // theshold = 1.1 > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1.1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active threshold is 1") - public void testActiveTheshold02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active threshold is more than sum of weight") - public void testActiveTheshold03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.MAX_VALUE *2 + 5 > sum(weight) - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":4294967299," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," + "{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\",\"weight\":3}," + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":2147483647}" + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not" - + " be less than threshold in permission Active", response.getMessage().toStringUtf8()); - - } - - @Test(enabled = true, description = "Active threshold is Long.MAX_VALUE") - public void testActiveTheshold04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active threshold is Integer.MAX_VALUE") - public void testActiveTheshold05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":2147483647," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483646}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":2147483647}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java deleted file mode 100644 index 44463b368c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java +++ /dev/null @@ -1,489 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign09 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active doesn't have parent_id") - public void testActiveParent01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":4," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Active parent_id is exception condition") - public void testActiveParent02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"123\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"abc\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":" + null - + ",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":1,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":2,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":3,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":-1,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":2147483647,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":2147483648,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":-2147483648,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":-2147483649,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active parent_id is 0") - public void testActiveParent03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":0,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java deleted file mode 100644 index 31ce7e37c8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java +++ /dev/null @@ -1,651 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign10 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active weight is exception condition") - public void testActiveWeight01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-2147483648}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":0}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036854775808}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036855775828}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"12a\"}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036855775828}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":" - + null + "}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = Long.MIN -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036854775809}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1.1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active weight is 1") - public void testActiveWeight02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active weight is Integer.MAX_VALUE") - public void testActiveWeight03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":21474836471}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":21474836471}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active sum of weight is more than Long.MAX_VALUE") - public void testActiveWeight04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active weight is Long.MAX_VALUE") - public void testActiveWeight05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java deleted file mode 100644 index 2c0a4aa4696..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java +++ /dev/null @@ -1,1089 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign11 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active address is witness") - public void testActiveAddress01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":4," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is contract address") - public void testActiveAddress02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," + "{\"address\":\"" - + PublicMethed.getAddressString(testKey002) + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is inactive address") - public void testActiveAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":5," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey01); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is owner address") - public void testActiveAddress04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is exception condition") - public void testActiveAddress05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = same address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : address should be distinct" + " in permission Active", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - fakeAddress = null; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = 1.1 - fakeAddress = "1.1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - - } - - @Test(enabled = true, description = "Active address count is 5") - public void testActiveAddress06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - activePermissionKeys.add(tmpKey02); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"" - + ",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(5, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(tmpKey01); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - - } - - @Test(enabled = true, description = "Active address count is more than 5") - public void testActiveAddress07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : number of keys in permission should" + " not be greater than 5", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active address count is 0") - public void testActiveAddress08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active address count is 1") - public void testActiveAddress09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(witnessKey001); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission count is 8") - public void testActiveAddress10() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - activePermissionKeys.add(tmpKey02); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":5," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":7," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":9," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":11," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":11," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(40, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(tmpKey01); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 9, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission count is 9") - public void testActiveAddress11() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active8\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is too many", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active permission count is 8, " - + "sum of weight is less than threshold") - public void testActiveAddress12() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should" - + " not be less than threshold in permission Active", response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java deleted file mode 100644 index 2f7ba226b32..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java +++ /dev/null @@ -1,501 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign12 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active type is exception condition") - public void testActiveType01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // type = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-2147483648,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":0,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036854775808," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036855775828," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036854775809," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":\"12a\",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":\"\",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":" + null + ",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":9223372036854775807," - + "\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":9223372036854775808," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":1.1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Active type is 2.9") - public void testActiveType02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long needCoin = updateAccountPermissionFee; - - PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2.9,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":21}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java deleted file mode 100644 index 2dd2a2c8d67..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java +++ /dev/null @@ -1,845 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign13 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness permission_name is witness") - public void testWitnessName01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed - .sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is witness12") - public void testWitnessName02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000L, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is \"123\"") - public void testWitnessName03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"123\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is \"\"") - public void testWitnessName04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness permission_name is null") - public void testWitnessName05() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":" + null - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness doesn't have permission_name") - public void testWitnessName06() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness permission_name is 123") - public void testWitnessName07() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"permission_name\":123,\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is 0.1") - public void testWitnessName08() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"permission_name\":\"0.1\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name length is 32") - public void testWitnessName09() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":" - + "{\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - - @Test(enabled = true, description = "Witness permission_name length is 33") - public void testWitnessName10() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":" - + "{\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java deleted file mode 100644 index 25fadd1e082..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java +++ /dev/null @@ -1,699 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign14 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness threshold is exception condition") - public void testWitnessThreshold01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // theshold = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-2147483648,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":0,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036855775828,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036854775809,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = "12a" - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":\"12a\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":\"\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":" + null + ",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = Long.MAX_VALUE < sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not be" - + " less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - // theshold = Long.MAX_VALUE + 1 > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1.1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - Assert.assertTrue(PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - @Test(enabled = true, description = "Witness threshold is 1") - public void testWitnessThreshold02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness threshold is more than sum of weight") - public void testWitnessThreshold03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold > sum(weight) - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":4294967299,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not be" - + " less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - // threshold = Integer.MAX_VALUE > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight " - + "should not be less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness threshold is Long.MAX_VALUE") - public void testWitnessThreshold04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java deleted file mode 100644 index a0e7124bd69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java +++ /dev/null @@ -1,597 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign15 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Witness doesn't have parent_id") - public void testWitnessParent01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness parent_id is exception condition") - public void testWitnessParent02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"123\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 123 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":123,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"abc\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":" + null + ",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":1,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":3,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-1,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2147483647,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2147483648,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-2147483648,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-2147483649,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness parent_id is 0") - public void testWitnessParent03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":0,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java deleted file mode 100644 index 8504f12df7b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java +++ /dev/null @@ -1,574 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign16 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness weight is exception condition") - public void testWitnessWeight01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":0}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-9223372036854775808}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-9223372036855775828}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"12a\"}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"\"}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":" + null + "}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":9223372036854775808}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1.1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - @Test(enabled = true, description = "Witness weight is 1") - public void testWitnessWeight02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness weight is Integer.MAX_VALUE") - public void testWitnessWeight03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness weight is Long.MAX_VALUE") - public void testWitnessWeight04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java deleted file mode 100644 index 735933714fc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java +++ /dev/null @@ -1,735 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign17 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness address is witness") - public void testWitnessAddress01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is contract") - public void testWitnessAddress02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is inactive address") - public void testWitnessAddress03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is owner_address") - public void testWitnessAddress04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is exception condition") - public void testWitnessAddress05() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = owner_address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission's key count should be 1", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, fakeAddress.getBytes(), ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = "1.1" - fakeAddress = "1.1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness address account is 5") - public void testWitnessAddress06() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission's key count should be 1", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address account is 0") - public void testWitnessAddress07() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java deleted file mode 100644 index 809f7d484ec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java +++ /dev/null @@ -1,612 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign18 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness type is 1") - public void testWitnessType01() { - // type = 1 - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness type is exception condition") - public void testWitnessType02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // type = 2 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":2,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":0,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036855775828,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":\"12a\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: For input string: \"12a\""); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":" + null + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":2147483647,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775807,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036854775809,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness type is 1.5") - public void testWitnessType03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1.5,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java deleted file mode 100644 index a2a61d4d5b2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java +++ /dev/null @@ -1,647 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign19 { - - public static final String DEFAULT_OPERATION = - "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active operation is ContractType.TransferContract_VALUE") - public void testActiveOperations01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - List activePermissionKeys2 = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - activePermissionKeys2.add(witnessKey001); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operationsTransfer = PublicMethedForMutiSign.getOperations(ints); - Integer[] ints2 = {ContractType.TransferAssetContract_VALUE}; - String operationsTransferAsset = PublicMethedForMutiSign.getOperations(ints2); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operationsTransfer + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operationsTransferAsset + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "]}]}"; - - Assert.assertTrue( - PublicMethedForMutiSign.accountPermissionUpdateWithPermissionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign - .getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 3, ownerKey, - blockingStubFull, - activePermissionKeys2.toArray(new String[activePermissionKeys2.size()]))); - - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys2.toArray(new String[activePermissionKeys2.size()]))); - - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - - } - - @Test(enabled = true, description = "Active operation is" - + " 0000000000000000000000000000000000000000000000000000000000000000") - public void testActiveOperations02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"0000000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue( - PublicMethedForMutiSign.accountPermissionUpdateWithPermissionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, PublicMethedForMutiSign - .getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Active operation include invalid contract") - public void testActiveOperations03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // operation include invalid 99 contract - Integer[] ints = {0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 31, - 32, 33, 41, 42, 43, 44, 45, 99}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 99 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation's length is less then 64, - // 63: 7fff1fc0033e000000000000000000000000000000000000000000000000000 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 21 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation's length is less then 64, - // 62: 7fff1fc0033e00000000000000000000000000000000000000000000000000 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // operation's length is more then 64, - // 65: 7fff1fc0033e00000000000000000000000000000000000000000000000000000 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":" - + "\"7fff1fc0033e00000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // operation's length is more then 64, - // 66: 7fff1fc0033e00000000000000000000000000000000000000000000000000000 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":" - + "\"7fff1fc0033e000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // oprations = "12aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - // same result 12eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - - operations = "12aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 21 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation = "" - - operations = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // Operation = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // Operation = null - operations = null; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (org.bouncycastle.util.encoders.DecoderException e) { - logger.info("org.bouncycastle.util.encoders.DecoderException !"); - ret = true; - } - Assert.assertTrue(ret); - - // no Operation - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner sets operation") - public void testActiveOperations04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Owner permission needn't operations", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Witness sets operation") - public void testActiveOperations05() { - String ownerKey = witnessKey001; - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission needn't operations", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java deleted file mode 100644 index e6cc4123bc0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java +++ /dev/null @@ -1,518 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign20 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner address is witness") - public void testOwnerAddress01() { - // address = witness - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed - .freezeBalanceForReceiver(fromAddress, 50000000L, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull); - PublicMethed - .freezeBalanceForReceiver(fromAddress, 50000000L, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull); - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner address is witness with exception condition") - public void testOwnerAddress02() { - // address = witness, without witness permission - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission is missed", - response.getMessage().toStringUtf8()); - - // address = witness, without active permission - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // address = witness, without owner permission - accountPermissionJson = "{\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission is missed", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Owner address is normal address with exception condition") - public void testOwnerAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - // address = normal address, with witness permission - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : account isn't witness can't set" + " witness permission", - response.getMessage().toStringUtf8()); - - // address = normal address, without owner permission - accountPermissionJson = - "{\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission is missed", - response.getMessage().toStringUtf8()); - - // address = normal address, without active permission - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // address = contract address - byte[] ownerAddress02 = contractTronDiceAddr.getBytes(); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress02, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = not active address - ECKey ecKeyTmp = new ECKey(Utils.getRandom()); - final byte[] ownerAddressTmp = ecKeyTmp.getAddress(); - final String ownerKeyTmp = ByteArray.toHexString(ecKeyTmp.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddressTmp, ownerKeyTmp, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : ownerAddress account does not exist", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = short address - - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = - fakeAddress = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = null - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = "1ab(*c" - fakeAddress = "1ab(*c"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull); - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java deleted file mode 100644 index eafca020b4a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java +++ /dev/null @@ -1,228 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign21 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Permission Count is in exception condition") - public void testPermissionCount01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - // count = 1 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // count = 0 - accountPermissionJson = "[]"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("com.alibaba.fastjson.JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Permission Count is 4") - public void testPermissionCount02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java deleted file mode 100644 index f56eef85291..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java +++ /dev/null @@ -1,682 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.tron.api.GrpcAPI.Return.response_code.SIGERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign22 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Sign permission transaction by owner permission") - public void test01SignByOwnerKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(ownerKey); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - ownerPermissionKeys.add(testKey002); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Sign normal transaction by owner permission") - public void test02SignByOwnerKeyForNormal() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - logger.info("** update owner permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(ownerKey); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(testKey002); - - logger.info("** trigger a normal permission"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 0, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1_000000); - } - - - @Test(enabled = true, description = "Sign normal transaction by active permission") - public void test03SignByActiveKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - List activePermissionKeys = new ArrayList<>(); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - activePermissionKeys.add(normalKey001); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(normalKey001) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** update owner permission to two address"); - logger.info("** trigger a normal permission"); - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 0, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @Test(enabled = true, description = "Sign permission transaction by active permission") - public void test04SignByActiveKeyForPermission() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - Integer[] ints = {ContractType.AccountPermissionUpdateContract_VALUE}; - final String operations = PublicMethedForMutiSign.getOperations(ints); - - PublicMethed.printAddress(ownerKey); - - List activePermissionKeys = new ArrayList<>(); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - activePermissionKeys.add(normalKey001); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," + "\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," + "{\"address\":\"" - + PublicMethed.getAddressString(normalKey001) + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, 2, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Sign permission transaction" - + " by address which is out of permission list") - public void test06SignByOtherKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(normalKey001); - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertThat(response.getMessage().toStringUtf8(), - containsString("it is not contained of permission")); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Sign permission transaction " + "by empty permission list") - public void test07SignByEmptyObjectKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String[] ownerPermissionKeys = new String[0]; - PublicMethed.printAddress(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertEquals("validate signature error miss sig or contract", - response.getMessage().toStringUtf8()); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Sign permission transaction by empty address") - public void test08SignByEmptyKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String[] ownerPermissionKeys = new String[1]; - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys[0] = ""; - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - - Assert.assertTrue(ret); - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Sign permission transaction by invalid address") - public void test07SignByStringKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - String emptyKey = "abc1222"; - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + emptyKey + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(emptyKey); - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerKey.getBytes(), ownerKey, - blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Set same permission") - public void test08RepeatUpdateSamePermission() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Sign permission transaction " - + "by active address and default permissionId") - public void test09SignListMoreThanPermissionKeys() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(testKey002); - ownerPermissionKeys.add(ownerKey); - - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertEquals( - "validate signature error Signature count " + "is 2 more than key counts of permission : 1", - response.getMessage().toStringUtf8()); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java deleted file mode 100644 index c2ec7fb39a3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java +++ /dev/null @@ -1,1015 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.PERMISSION_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign23 { - - private static final String AVAILABLE_OPERATION = - "7fff1fc0037e0000000000000000000000000000000000000000000000000000"; - private static final String DEFAULT_OPERATION = - "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Add sign for multi sign normal transaction") - public void test01MultiSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, witnessKey001, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Transaction transaction3 = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction4 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction3,blockingStubFull)); - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction4,blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @Test(enabled = true, description = "Add sign for multi sign permission transaction") - public void test02MultiSignPermissionTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.AccountPermissionUpdateContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Transaction transaction = PublicMethedForMutiSign.accountPermissionUpdateWithoutSign( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "" - + "Add sign for single sign normal transaction,get approve list") - public void test03SingleSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - - } - - @Test(enabled = true, description = "Add sign for normal transaction " - + "with address not in permission list") - public void test06SignFailedTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, testKey002, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Add sign for timeout normal transaction,get approve list") - public void test07TimeoutTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - try { - Thread.sleep(70000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign.getTransactionSignWeight( - transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - logger.info("Base58.encode58Check(test001Address)1:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - - } - - @Test(enabled = true, description = "Add sign for empty transaction,get approve list") - public void test08EmptyTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - logger.info("** created an empty transaction"); - - AccountPermissionUpdateContract.Builder builder = - AccountPermissionUpdateContract.newBuilder(); - - AccountPermissionUpdateContract contract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.accountPermissionUpdate(contract); - Transaction transaction = transactionExtention.getTransaction(); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, ownerKey, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction, blockingStubFull); - logger.info("Before broadcast transactionApprovedList info :\n" + transactionApprovedList); - Assert.assertEquals("class java.lang.IndexOutOfBoundsException : Index: 0", - transactionApprovedList.getResult().getMessage()); - Assert.assertFalse(PublicMethedForMutiSign - .broadcastTransaction(transaction1, blockingStubFull)); - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - Assert.assertEquals("class java.lang.IndexOutOfBoundsException : Index: 0", - transactionApprovedList.getResult().getMessage()); - } - - @Test(enabled = true, description = "Add sign for fake transaction,get approve list") - public void test09ErrorTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a fake transaction"); - Transaction transaction = PublicMethedForMutiSign - .createFakeTransaction(ownerAddress, 1_000_000L, ownerAddress); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast permission TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - @Test(enabled = true, description = "Add sign transaction with mix order") - public void test10MultiSignNormalTransactionWithMixOrder() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = PublicMethedForMutiSign.getTransactionSignWeight( - transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString( - transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast1 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(1, txWeight.getCurrentWeight()); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Transaction transaction3 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction2, witnessKey001, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction3.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction3, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(3, txWeight.getCurrentWeight()); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction3, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Add sign transaction with same address") - public void test11MultiSignNormalTransactionBySameAccount() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = - PublicMethedForMutiSign.getTransactionSignWeight(transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast1 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(1, txWeight.getCurrentWeight()); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Transaction transaction3 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction2, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction3.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction3, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(PERMISSION_ERROR, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - Assert.assertThat(txWeight.getResult().getMessage(), - containsString("has signed twice!")); - - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction( - transaction3, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Add sign transaction with null address") - public void test12MultiSignNormalTransactionByNullKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = - PublicMethedForMutiSign.getTransactionSignWeight(transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = null; - boolean ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, null, 2, blockingStubFull); - } catch (NullPointerException e) { - logger.info("java.lang.NullPointerException"); - ret = true; - } - Assert.assertTrue(ret); - - ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, "", 2, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: Zero length BigInteger"); - ret = true; - } catch (NullPointerException e) { - logger.info("NullPointerException"); - ret = true; - } - Assert.assertTrue(ret); - - ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, "abcd1234", 2, blockingStubFull); - } catch (Exception e) { - logger.info("Exception!!"); - ret = true; - } - Assert.assertFalse(ret); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(PERMISSION_ERROR, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - Assert.assertThat(txWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java deleted file mode 100644 index a96d5e165b1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java +++ /dev/null @@ -1,280 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign24 { - - private static final String AVAILABLE_OPERATION - = "7fff1fc0037e0000000000000000000000000000000000000000000000000000"; - private static final String DEFAULT_OPERATION - = "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Broadcast multi sign normal transaction") - public void test01BroadcastMultiSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner1\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 0, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, testKey002, 0, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Broadcast single owner sign normal transaction") - public void test03BroadcastSingleSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, testKey002, 0, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java deleted file mode 100644 index bdcd997afe8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java +++ /dev/null @@ -1,780 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign26 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use acticve address to sign," - + "not meet the requirements.Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - logger.info("transactionSignWeight:" + transactionSignWeight); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList3 = test001AddressAccount3.getActivePermissionList(); - Permission ownerPermission3 = test001AddressAccount3.getOwnerPermission(); - Permission witnessPermission3 = test001AddressAccount3.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList3); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission3)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission3)); - - final Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, updateAccountPermissionFee); - logger.info("returnResult:"); - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("Permission denied")); - - - } - - @Test(enabled = true, description = "Sendcoin,use acticve address to sign," - + "meet the all requirements.Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_1() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - Assert.assertEquals(0, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - final Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - } - - - @Test(enabled = true, description = "Sendcoin,use owner address to sign," - + "Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_2() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address" - + "\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = dev001Key; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString1)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - final Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - @Test(enabled = true, description = "AccountPermissionUpdate transaction," - + "use owner address to sign,Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_3() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson3 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson3, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - final Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey2, 0, blockingStubFull); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address" - + "\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = dev001Key; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString1)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - - - - @Test(enabled = true, description = "Sendcoin,Delete the owner address," - + "use the address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_AfterSign() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - logger.info("1-----------------------"); - - final Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - - } - - @Test(enabled = true, description = "AccountPermissionUpdate transaction," - + "Delete the owner address,use the address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_AfterSign_4() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 3 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - String accountPermissionJson3 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - final Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson3, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java deleted file mode 100644 index 5d25db9e159..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java +++ /dev/null @@ -1,604 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign27 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionID not same in activelist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_3() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionID not same in activelist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_4() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionID not same in activelist address to sign," - + "meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_6() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use not in permissionlist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_7() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use in active address to sign,not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_8() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use in active address to sign, meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_9() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java deleted file mode 100644 index dda33e99e0c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java +++ /dev/null @@ -1,1134 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign28 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = - "Sendcoin permission id 2,use not in permissionlist address sign." - + "Then use in active address permission id 2 to sign ,broadcastTransaction.") - public void testMultiUpdatepermissions_10() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - - } - - @Test(enabled = true, description = - "Sendcoin permission id 2,use not in permissionlist address sign." - + "Then use in active address to sign,no right to sendcoin,broadcastTransaction.") - public void testMultiUpdatepermissions_11() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - - Assert.assertEquals(balance1, balance2); - - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address in permission id 3 sign." - + "Then use active address in permission id 2to sign.broadcastTransaction.") - public void testMultiUpdatepermissions_12() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "sum weight > threshold") - public void testMultiUpdatepermissions_13() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + multiSignFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - final long balance1 = test001AddressAccount1.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, multiSignFee + 1); - - - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionId not same in active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_14() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("ENOUGH_PERMISSION")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionId not same active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_15() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = - "Sendcoin,use not in permissionlist address sign," - + "Then use owner address to sign,meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_16() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = - "Sendcoin,use not in permissionlist address sign, meet all requirements." - + "Then use owner address to sign,,broadcastTransaction.") - public void testMultiUpdatepermissions_17() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address sign, meet all requirements." - + "Then use owner address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_18() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address sign, meet all requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_19() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2,use owner address sign." - + "Then use active address to sign, meet permission id.broadcastTransaction.") - public void testMultiUpdatepermissions_20() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - long balance = test001AddressAccount.getBalance(); - - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - final long balance1 = test001AddressAccount1.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use not in permissionlist address sign." - + "Then use owner address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_21() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java deleted file mode 100644 index ec67d890388..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java +++ /dev/null @@ -1,656 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign29 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionID same in active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_23() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin with permission id 0,use owner address sign," - + "Then use owner address to sign, sum weight > threshold,broadcastTransaction.") - public void testMultiUpdatepermissions_24() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\":" + "\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed - .getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, multiSignFee + 1); - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use owner address to sign, not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_25() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_27() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign,meet all requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_28() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use active address to sign no permission id,broadcastTransaction.") - public void testMultiUpdatepermissions_29() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance, balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use active address to sign with permission id 2,broadcastTransaction.") - public void testMultiUpdatepermissions_30() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - /** - * constructor. - */ - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java deleted file mode 100644 index 854c2b7c986..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign30 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = - "Sendcoin,use active address no right to sendcoin sign(weight< threshold)." - + "Then use the same address to sign(weight>=threshold),broadcastTransaction.") - public void testMultiUpdatepermissions_32() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}" - + ",{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java deleted file mode 100644 index 7aa7403c631..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java +++ /dev/null @@ -1,681 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign31 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - private ManagedChannel channelSolidity = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = - "Sendcoin,use active address sign, meet all requirements,broadcast,Then use the same" - + " permissionID active address to sign, meet all requirements,broadcast.") - public void testMultiUpdatepermissions_34() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" - + "" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - - Assert.assertEquals(balance1 - balance2, 1L); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("DUP_TRANSACTION_ERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - - } - - - @Test(enabled = true, description = - "Sendcoin,use active address sign," - + "not meet the requirements broadcastTransaction.Then use the same" - + " permissionID active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_35() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" - + "" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - Assert.assertEquals(balance1, balance2); - - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8().toLowerCase(), - containsString("validate signature error: permission denied".toLowerCase())); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - - logger.info("transaction1:" + transactionSignWeight1); - - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - logger.info("balance3:" + balance3); - Assert.assertEquals(balance3, balance2); - - - } - - @Test(enabled = true, description = - "Sendcoin,use owner address sign, broadcast,Then use other owner address to sign,broadcast.") - public void testMultiUpdatepermissions_36() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(returnResult1.getResult()); - - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("DUP_TRANSACTION_ERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2, balance3); - } - - @Test(enabled = true, description = - "Sendcoin permission id 3,use active address in permission id 2 sign," - + "Then use active address" - + " in permission id 3 to sign, meet all requirements.broadcastTransaction.") - public void testMultiUpdatepermissions_37() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - //Assert.assertTrue(returnResult1.getResult()); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2, balance3); - - } - - @Test(enabled = true, description = - "Sendcoin,use active address sign meet all requirements,broadcast,Then use active address" - + "in wrong permission id to sign,not meet the requirements.broadcast.") - public void testMultiUpdatepermissions_38() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - } - - @Test(enabled = true, description = - "Sendcoin,use active address sign, meet all requirements,Then use the other permissionID " - + "in active address to sign, meet all requirements.broadcastTransaction.") - public void testMultiUpdatepermissions_39() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1L); - - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java deleted file mode 100644 index 29c8c216d69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java +++ /dev/null @@ -1,168 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign33 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "Active address fall back into only myself") - public void testMultiSignActiveAddress() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\"," - + "\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java deleted file mode 100644 index 5205a5b4265..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java +++ /dev/null @@ -1,231 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign34 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "SR witness,sendcoin, use witnessPermission address sign.") - public void testMultiUpdatepermissions_42() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 1, testWitnesses, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - final TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance, balance1); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission for this, does not exist!")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("permission isn't exit")); - - } - - @Test(enabled = true, description = "SR witness,sendcoin, use active address sign.") - public void testMultiUpdatepermissions_43() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 2, testWitnesses, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - final TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission for this, does not exist!")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance, balance1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("permission isn't exit")); - - } - - - @Test(enabled = true, description = "SR witness,sendcoin, use owner address sign.") - public void testMultiUpdatepermissions_44() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info("balance: " + balance); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 0, testWitnesses, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1: " + balance1); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, 1); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java deleted file mode 100644 index 68808226df9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java +++ /dev/null @@ -1,299 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign35 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "update active operation," - + " use active address meet all requirement") - public void testMultiUpdatepermissions_45() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[5]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "7fff1fc0037e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[5]; - permissionKeyString1[0] = sendAccountKey4; - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey4, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult:" + returnResult); - Assert.assertTrue(returnResult.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - final long balance2 = test001AddressAccount2.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - - - } - - @Test(enabled = true, description = "update active operation," - + " use active address no right update sign, broadcast") - public void testMultiUpdatepermissions_46() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[5]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[5]; - permissionKeyString1[0] = sendAccountKey4; - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey4, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult:" + returnResult); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - final long balance2 = test001AddressAccount2.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert.assertEquals(balance1, balance2); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java deleted file mode 100644 index 1fb3bca6992..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java +++ /dev/null @@ -1,549 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionApprovedList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign36 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "two owner address sign update permission transaction " - + "sum(weight)==threshold,get approve list") - public void getTransactionApprovedList_01() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, dev001Key, 0, blockingStubFull); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction2, blockingStubFull); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test001Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(1).toByteArray())); - Assert.assertEquals(2, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(0, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Account test001AddressAccount1 = PublicMethed - .queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - - } - - - @Test(enabled = true, description = - "sendcoin,use active address sign meet all requirement,delete " - + "the used active address," - + "and change active no right to sendcoin. get first transaction approve list") - public void getTransactionApprovedList_02() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey2, 2, blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Account test001AddressAccount2 = PublicMethed.queryAccount(sendAccountKey2, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - - } - - @Test(enabled = true, description = "sendcoin,use active address sign," - + "sum(weight)==threshold,get approve list") - public void getTransactionApprovedList_03() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction2, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test003Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(1).toByteArray())); - Assert.assertEquals(2, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - @Test(enabled = true, description = "Multi-signature unfinished transaction,get approve list") - public void getTransactionApprovedList_06() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - - @Test(enabled = true, description = "sendcoin transaction in owner permission," - + "but sign use active address," - + "get approve list") - public void getTransactionApprovedList_07() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(0, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - - /** - * constructor. - */ - public Protocol.Transaction createFakeTransaction(byte[] toAddrss, Long amount, - byte[] fromAddress) { - - BalanceContract.TransferContract contract = BalanceContract.TransferContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(fromAddress)) - .setToAddress(ByteString.copyFrom(toAddrss)) - .setAmount(amount) - .build(); - Protocol.Transaction transaction = createTransaction(contract, ContractType.TransferContract); - - return transaction; - } - - private Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter( - Any.pack(message)).build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long gtime = count.incrementAndGet() + time; - String ref = "" + gtime; - - transaction = setReference(transaction, gtime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, gtime); - - return transaction; - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java deleted file mode 100644 index 2f6ebf69130..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java +++ /dev/null @@ -1,416 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign37 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = - "Sendcoin with permission id 0,use owner address sign, weight permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert - .assertThat(returnResult2.getMessage().toStringUtf8(), - containsString( - "Signature count is 2 more than key counts of permission : 1")); - Assert.assertEquals(balance1, balance3); - } - - - @Test(enabled = true, description = - "Sendcoin,use owner address sign, not meet all requirements.Then use " - + " active address to sign, not meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_48() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertThat(returnResult2.getMessage().toStringUtf8(), - containsString("Permission denied")); - Assert.assertEquals(balance1, balance3); - } - - @Test(enabled = true, description = - "Sendcoin,use two owner address sign,sum(weight)==threshold,broadcastTransaction.") - public void testMultiUpdatepermissions_49() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + multiSignFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("ENOUGH_PERMISSION")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance1 - balance3, multiSignFee + 1); - Assert.assertTrue(returnResult2.getResult()); - } - - /** - * constructor. - */ - - private Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter( - Any.pack(message)).build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long gtime = count.incrementAndGet() + time; - String ref = "" + gtime; - - transaction = setReference(transaction, gtime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, gtime); - - return transaction; - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java deleted file mode 100644 index c179d5b9821..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountPermissionUpdateTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1UpdatePermission() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId1(accountPermissionJson1, ownerAddress, ownerKey, - blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java deleted file mode 100644 index 68513fd3a58..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java +++ /dev/null @@ -1,192 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountPermissionUpdateTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1UpdatePermission() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId1(accountPermissionJson1, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java deleted file mode 100644 index a2d7790bf9d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - private String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static byte[] randomBytes(int length) { - // generate the random number - byte[] result = new byte[length]; - new Random().nextBytes(result); - result[0] = Wallet.getAddressPreFixByte(); - return result; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - //operations = "77ff1fc0037e0100000000000000000000000000000000000000000000000000"; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 10; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - byte[] accountName = String.valueOf(System.currentTimeMillis()).getBytes(); - Assert.assertTrue(PublicMethedForMutiSign.createAccount1( - ownerAddress, newAddress, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(accountName, - ownerAddress, ownerKey, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 0, ownerKey, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 0, ownerKey, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, null, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, 0, ownerKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, 0, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 11 + 2000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java deleted file mode 100644 index ec26f326285..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java +++ /dev/null @@ -1,217 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountTest002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static byte[] randomBytes(int length) { - // generate the random number - byte[] result = new byte[length]; - new Random().nextBytes(result); - result[0] = Wallet.getAddressPreFixByte(); - return result; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 10; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - byte[] accountName = "11z2112310".getBytes(); - Assert.assertTrue(PublicMethedForMutiSign.createAccount1( - ownerAddress, newAddress, ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(accountName, - ownerAddress, ownerKey, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, null, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, 2, permissionKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, 2, permissionKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 10 + 1000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java deleted file mode 100644 index 8b62df24b37..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java +++ /dev/null @@ -1,348 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAssetTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId1(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId1(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - 0, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 0, - blockingStubFull, ownerKeyString); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 0, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java deleted file mode 100644 index 2f829e1fcb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java +++ /dev/null @@ -1,348 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAssetTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId1(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId1(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - 2, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 2, - blockingStubFull, permissionKeyString); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 2, blockingStubFull, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java deleted file mode 100644 index cce4a0c4660..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java +++ /dev/null @@ -1,311 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignClearContractAbiTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test1MutiSignForClearContractAbi() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test2MutiSignForClearContractAbiForDefault() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test3MutiSignForClearContractAbiForDefault() { - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String[] activeDefaultKeyString = new String[1]; - - activeDefaultKeyString[0] = ownerKey; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, activeDefaultKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, activeDefaultKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java deleted file mode 100644 index f8cf2b07a3d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java +++ /dev/null @@ -1,414 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignExchangeContractTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - final long needCoin = updateAccountPermissionFee + multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java deleted file mode 100644 index 5edc03924e3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java +++ /dev/null @@ -1,414 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignExchangeContractTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - final long needCoin = updateAccountPermissionFee + multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java deleted file mode 100644 index 13be09fc9b9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java +++ /dev/null @@ -1,217 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignMarketAssetTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - ECKey ecKey0 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey0.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey0.getPrivKeyBytes()); - - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(testAddress001, 20000_000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001, - "MarketAsset" + start, - 100_000000L, - 1,1, - start, end,1,"MarketAsset","MarketAsset.com",10000L,10000L,1L, 1L,testKey001, - blockingStubFull)); - Long balanceBefore = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = testKey001; - ownerKeyString[1] = testKey002; - - // operation include MarketSellAssetContract(52) - Integer[] ints = {0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 31, - 32, 33, 41, 42, 43, 44, 45, 48, 49, 52, 53}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, testAddress001, testKey001, - blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "MutiSignForMarketSellAsset with active_permissions") - public void testMutiSignForMarketSellAsset001() { - // MarketSellAsset - ByteString assetAccountId = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - Assert.assertTrue(PublicMethedForMutiSign - .marketSellAsset(testAddress001,assetAccountId.toByteArray(),10,"_".getBytes(),10,2, - permissionKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - MarketOrderList marketOrder = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get(); - Assert.assertEquals(marketOrderCountBefore + 1, marketOrder.getOrdersCount()); - } - - @Test(enabled = true, description = "MutiSignForMarketSellAsset with owner_permission") - public void testMutiSignForMarketSellAsset002() { - // MarketSellAsset - ByteString assetAccountId = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign - .marketSellAsset(testAddress001,assetAccountId.toByteArray(),10,"_".getBytes(),10,0, - ownerKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - MarketOrderList marketOrder = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get(); - Assert.assertEquals(marketOrderCountBefore + 1, marketOrder.getOrdersCount()); - } - - - @Test(enabled = true, dependsOnMethods = "testMutiSignForMarketSellAsset001", - description = "MutiSignForMarketOrderCancel with active_permissions") - public void testMutiSignForMarketOrderCancel001() { - // MarketOrderCancel - - ByteString orderId = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrders(0).getOrderId(); - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign.marketCancelOrder(testAddress001, - orderId.toByteArray(),2,permissionKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(marketOrderCountBefore - 1, PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount()); - - } - - @Test(enabled = true, dependsOnMethods = "testMutiSignForMarketSellAsset002", - description = "MutiSignForMarketOrderCancel with owner_permission") - public void testMutiSignForMarketOrderCancel002() { - // MarketOrderCancel - - ByteString orderId = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrders(0).getOrderId(); - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign.marketCancelOrder(testAddress001, - orderId.toByteArray(),0,ownerKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(marketOrderCountBefore - 1, PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount()); - - } - - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java deleted file mode 100644 index 73d5c0071f6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignProposalTest { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 5; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - ownerKeyString[1] = testKey002; - - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":2,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0037e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(manager1Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java deleted file mode 100644 index 6724fe22d97..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java +++ /dev/null @@ -1,169 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignProposalTest002 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue(balanceBefore - balanceAfter >= needcoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java deleted file mode 100644 index 2b1c4943504..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignSmartContractTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 0, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract1(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.getTransactionById(txid, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java deleted file mode 100644 index 655518c4ab9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignSmartContractTest002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract1(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.getTransactionById(txid, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java deleted file mode 100644 index 0958518d43d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignUpdataBrokerageTest { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForUpdateBrokerage() { - long needcoin = updateAccountPermissionFee * 2 + multiSignFee * 5; - Assert.assertTrue(PublicMethed - .sendcoin(witness001Address, needcoin + 1000000L, fromAddress, testKey002, - blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - ownerKeyString[1] = testKey002; - - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":2,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," + "\"weight\":1},{\"address\":\"" + PublicMethed - .getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0300000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(manager1Key) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Update brokerage - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign - .updateBrokerage(witness001Address, 70, witnessKey001, 2, permissionKeyString, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // wait a MaintenanceTimeInterval - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":1,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," + "\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0300000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java deleted file mode 100644 index a2190cc24ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java +++ /dev/null @@ -1,145 +0,0 @@ -package stest.tron.wallet.dailybuild.originenergylimit; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractOriginEnergyLimit001 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey1.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress3); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - //Origin_energy_limit001,028,029 - @Test(enabled = true, description = "Boundary value and update test") - public void testOrigin_energy_limit001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/contractOriginEnergyLimit001.sol"; - String contractName = "findArgsContractTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String contractAddress = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, -1, "0", 0, - null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(contractAddress == null); - - String contractAddress1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 0, "0", 0, - null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - Assert.assertTrue(contractAddress1 == null); - - byte[] contractAddress2 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 9223372036854775807L, "0", - 0, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, -1L, - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, 0L, - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract1 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract1.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertTrue(PublicMethed.updateEnergyLimit(contractAddress2, - 9223372036854775807L, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull)); - SmartContract smartContract2 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract2.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertTrue(PublicMethed.updateEnergyLimit(contractAddress2, 'c', - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract3 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertEquals(smartContract3.getOriginEnergyLimit(), 99); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, 1L, - testNetAccountKey, testNetAccountAddress, blockingStubFull)); - SmartContract smartContract4 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertEquals(smartContract4.getOriginEnergyLimit(), 99); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java deleted file mode 100644 index c2ca4ff01a0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java +++ /dev/null @@ -1,378 +0,0 @@ -package stest.tron.wallet.dailybuild.originenergylimit; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractOriginEnergyLimit004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - private long getAvailableFrozenEnergy(byte[] accountAddress) { - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountAddress, - blockingStubFull); - long energyLimit = resourceInfo.getEnergyLimit(); - long energyUsed = resourceInfo.getEnergyUsed(); - return energyLimit - energyUsed; - } - - private long getUserAvailableEnergy(byte[] userAddress) { - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(userAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(userAddress, blockingStubFull); - long balance = info.getBalance(); - long energyLimit = resourceInfo.getEnergyLimit(); - long userAvaliableFrozenEnergy = getAvailableFrozenEnergy(userAddress); - return balance / 100 + userAvaliableFrozenEnergy; - } - - private long getFeeLimit(String txid) { - Optional trsById = PublicMethed.getTransactionById(txid, blockingStubFull); - return trsById.get().getRawData().getFeeLimit(); - } - - private long getUserMax(byte[] userAddress, long feelimit) { - logger.info("User feeLimit: " + feelimit / 100); - logger.info("User UserAvaliableEnergy: " + getUserAvailableEnergy(userAddress)); - return Math.min(feelimit / 100, getUserAvailableEnergy(userAddress)); - } - - private long getOriginalEnergyLimit(byte[] contractAddress) { - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - return smartContract.getOriginEnergyLimit(); - } - - private long getConsumeUserResourcePercent(byte[] contractAddress) { - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - return smartContract.getConsumeUserResourcePercent(); - } - - private long getDevMax(byte[] devAddress, byte[] userAddress, long feeLimit, - byte[] contractAddress) { - long devMax = Math.min(getAvailableFrozenEnergy(devAddress), - getOriginalEnergyLimit(contractAddress)); - long p = getConsumeUserResourcePercent(contractAddress); - if (p != 0) { - logger.info("p: " + p); - devMax = Math.min(devMax, getUserMax(userAddress, feeLimit) * (100 - p) / p); - logger.info("Dev byUserPercent: " + getUserMax(userAddress, feeLimit) * (100 - p) / p); - } - logger.info("Dev AvaliableFrozenEnergy: " + getAvailableFrozenEnergy(devAddress)); - logger.info("Dev OriginalEnergyLimit: " + getOriginalEnergyLimit(contractAddress)); - return devMax; - } - - @Test(enabled = true, description = "Contract use Origin_energy_limit") - public void testOriginEnergyLimit() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // A2B1 - - //dev balance and Energy - long devTargetBalance = 10_000_000; - long devTargetEnergy = 70000; - - // deploy contract parameters - final long deployFeeLimit = maxFeeLimit; - final long consumeUserResourcePercent = 0; - final long originEnergyLimit = 1000; - - //dev balance and Energy - final long devTriggerTargetBalance = 0; - final long devTriggerTargetEnergy = 592; - - // user balance and Energy - final long userTargetBalance = 0; - final long userTargetEnergy = 2000L; - - // trigger contract parameter, maxFeeLimit 10000000 - final long triggerFeeLimit = maxFeeLimit; - final boolean expectRet = true; - - // count dev energy, balance - long devFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, - devTargetEnergy, blockingStubFull); - - long devNeedBalance = devTargetBalance + devFreezeBalanceSun; - - logger.info("need balance:" + devNeedBalance); - - // get balance - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, devNeedBalance, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // get energy - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, devFreezeBalanceSun, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before deploy, dev energy limit is " + Long.toString(devEnergyLimitBefore)); - logger.info("before deploy, dev energy usage is " + Long.toString(devEnergyUsageBefore)); - logger.info("before deploy, dev balance is " + Long.toString(devBalanceBefore)); - - String filePath = "src/test/resources/soliditycode/contractOriginEnergyLimit004.sol"; - String contractName = "findArgsContractTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - deployFeeLimit, 0L, consumeUserResourcePercent, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after deploy, dev energy limit is " + Long.toString(devEnergyLimitAfter)); - logger.info("after deploy, dev energy usage is " + Long.toString(devEnergyUsageAfter)); - logger.info("after deploy, dev balance is " + Long.toString(devBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - - ByteString contractAddressString = infoById.get().getContractAddress(); - contractAddress = contractAddressString.toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - - Assert.assertTrue(smartContract.getAbi() != null); - - Assert.assertTrue(devEnergyLimitAfter > 0); - Assert.assertTrue(devEnergyUsageAfter > 0); - Assert.assertEquals(devBalanceBefore, devBalanceAfter); - - // count dev energy, balance - devFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, - devTriggerTargetEnergy, blockingStubFull); - - devNeedBalance = devTriggerTargetBalance + devFreezeBalanceSun; - logger.info("dev need balance:" + devNeedBalance); - - // count user energy, balance - long userFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(user001Address, user001Key, - userTargetEnergy, blockingStubFull); - - long userNeedBalance = userTargetBalance + userFreezeBalanceSun; - - logger.info("User need balance:" + userNeedBalance); - - // get balance - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, devNeedBalance, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, userNeedBalance, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // get energy - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, devFreezeBalanceSun, - 0, 1, dev001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, userFreezeBalanceSun, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitBefore = accountResource.getEnergyLimit(); - devEnergyUsageBefore = accountResource.getEnergyUsed(); - devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev devEnergyLimitBefore is " - + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, dev devEnergyUsageBefore is " - + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, dev devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount( - user001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, user userEnergyLimitBefore is " - + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, user userEnergyUsageBefore is " - + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, user userBalanceBefore is " + Long.toString(userBalanceBefore)); - - logger.info("=================================="); - long userMax = getUserMax(user001Address, triggerFeeLimit); - long devMax = getDevMax(dev001Address, user001Address, triggerFeeLimit, contractAddress); - - logger.info("userMax: " + userMax); - logger.info("devMax: " + devMax); - logger.info("=================================="); - - String param = "\"" + 0 + "\""; - final String triggerTxid = PublicMethed - .triggerContract(contractAddress, "findArgsByIndexTest(uint256)", - param, false, 0, triggerFeeLimit, - user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitAfter = accountResource.getEnergyLimit(); - devEnergyUsageAfter = accountResource.getEnergyUsed(); - devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, dev devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, dev devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, dev devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("after trigger, user userEnergyLimitAfter is " - + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, user userEnergyUsageAfter is " - + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, user userBalanceAfter is " + Long.toString(userBalanceAfter)); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - boolean isSuccess = true; - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - logger.info("transaction failed with message: " + infoById.get().getResMessage()); - isSuccess = false; - } - - long fee = infoById.get().getFee(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - long originEnergyUsage = infoById.get().getReceipt().getOriginEnergyUsage(); - long energyTotalUsage = infoById.get().getReceipt().getEnergyUsageTotal(); - long netUsage = infoById.get().getReceipt().getNetUsage(); - long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee: " + fee); - logger.info("energyFee: " + energyFee); - logger.info("energyUsage: " + energyUsage); - logger.info("originEnergyUsage: " + originEnergyUsage); - logger.info("energyTotalUsage: " + energyTotalUsage); - logger.info("netUsage: " + netUsage); - logger.info("netFee: " + netFee); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - long devExpectCost = energyTotalUsage * (100 - consumeUserPercent) / 100; - long userExpectCost = energyTotalUsage - devExpectCost; - final long totalCost = devExpectCost + userExpectCost; - - logger.info("devExpectCost: " + devExpectCost); - logger.info("userExpectCost: " + userExpectCost); - - Assert.assertTrue(devEnergyLimitAfter > 0); - Assert.assertEquals(devBalanceBefore, devBalanceAfter); - - // dev original is the dev max expense A2B1 - Assert.assertEquals(getOriginalEnergyLimit(contractAddress), devMax); - - // DEV is enough to pay - Assert.assertEquals(originEnergyUsage, devExpectCost); - // Assert.assertEquals(devEnergyUsageAfter,devExpectCost + devEnergyUsageBefore); - // User Energy is enough to pay"); - Assert.assertEquals(energyUsage, userExpectCost); - Assert.assertEquals(userBalanceBefore, userBalanceAfter); - Assert.assertEquals(userEnergyUsageAfter, userEnergyUsageBefore); - Assert.assertEquals(userBalanceBefore, userBalanceAfter); - Assert.assertEquals(totalCost, energyTotalUsage); - - if (expectRet) { - Assert.assertTrue(isSuccess); - } else { - Assert.assertFalse(isSuccess); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java deleted file mode 100644 index a0ec6441b33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.dailybuild.transaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.TransactionIdList; -import org.tron.api.GrpcAPI.TransactionList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; - - -@Slf4j - -public class TransactionPendingQuery001 { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - final String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - String txid = null; - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - } - - @Test(enabled = true, description = "Test get pending size") - public void test01GetPendingSize() { - long pendingSizeInFullNode = 0; - int retryTimes = 100; - while (pendingSizeInFullNode == 0 && retryTimes-- > 0) { - PublicMethed.sendcoin(receiverAddress,1L,fromAddress,testKey002,blockingStubFull); - if (retryTimes % 5 == 0) { - pendingSizeInFullNode = blockingStubFull - .getPendingSize(EmptyMessage.newBuilder().build()).getNum(); - } - } - Assert.assertNotEquals(pendingSizeInFullNode,0); - } - - - @Test(enabled = true, description = "Test get pending transaction list") - public void test02GetPendingTransactionList() { - int retryTimes = 100; - TransactionIdList transactionList = blockingStubFull - .getTransactionListFromPending(EmptyMessage.newBuilder().build()); - while (transactionList.getTxIdCount() == 0 && retryTimes-- > 0) { - PublicMethed.sendcoin(receiverAddress,1L,fromAddress,testKey002,blockingStubFull); - if (retryTimes % 5 == 0) { - transactionList = blockingStubFull - .getTransactionListFromPending(EmptyMessage.newBuilder().build()); - } - } - Assert.assertNotEquals(transactionList.getTxIdCount(),0); - - txid = transactionList.getTxId(0); - - logger.info("txid:" + txid); - - } - - - @Test(enabled = true, description = "Test transaction from pending") - public void test03GetTransactionFromPending() { - Transaction transaction = PublicMethed.getTransactionFromPending(txid,blockingStubFull).get(); - Assert.assertEquals(ByteArray.toHexString(Sha256Hash - .hash(true, transaction.getRawData().toByteArray())),txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(receiverAddress, receiverKey, 1, receiverAddress, - blockingStubFull); - PublicMethed.freedResource(receiverAddress, receiverKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java deleted file mode 100644 index 66ffddb0633..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken001 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - - @Test(enabled = true, description = "DeployContract with correct tokenValue and tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - final String triggerTxid = PublicMethed - .triggerContract(transferTokenContractAddress, "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java deleted file mode 100644 index 83d4448645f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java +++ /dev/null @@ -1,285 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken002 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TriggerContract with correct tokenValue and tokenId") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 3100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 300_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken002.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - - PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 10; - callValue = 0; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after user trigger Contract has AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + contractAssetCount); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java deleted file mode 100644 index 4bc3cdab8cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java +++ /dev/null @@ -1,354 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken003 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountDev = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - } - - @Test(enabled = true, description = "DeployContract with exception condition") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //dev Create a new AssetIssue - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountDev = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountDev token name: " + tokenName); - logger.info("The assetAccountDev token ID: " + assetAccountDev.toStringUtf8()); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //user Create a new AssetIssue - Assert.assertTrue(PublicMethed - .createAssetIssue(user001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountUser = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountDev, blockingStubFull); - Long userAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountUser, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info( - "before dev has AssetId: " + assetAccountDev.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - logger.info( - "before dev has AssetId: " + assetAccountUser.toStringUtf8() + ", userAssetCountBefore: " - + userAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken003.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - // the tokenId is not exist - String fakeTokenId = Long.toString(Long.valueOf(assetAccountDev.toStringUtf8()) + 100); - Long fakeTokenValue = 100L; - - GrpcAPI.Return response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // deployer didn't have any such token - fakeTokenId = assetAccountUser.toStringUtf8(); - fakeTokenValue = 100L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance must greater than 0.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // deployer didn't have any Long.MAX_VALUE - fakeTokenId = Long.toString(Long.MAX_VALUE); - fakeTokenValue = 100L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // the tokenValue is not enough - fakeTokenId = assetAccountDev.toStringUtf8(); - fakeTokenValue = devAssetCountBefore + 100; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance is not sufficient.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenid is -1 - fakeTokenId = Long.toString(-1); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenid is 100_0000L - fakeTokenId = Long.toString(100_0000L); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenid is Long.MIN_VALUE - fakeTokenId = Long.toString(Long.MIN_VALUE); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenid is 0 - fakeTokenId = Long.toString(0); - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - ("contract validate error : invalid arguments " - + "with tokenValue = 100, tokenId = 0").toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenvalue is less than 0 - fakeTokenValue = -1L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - assetAccountDev.toStringUtf8(), fakeTokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenvalue is long.min - fakeTokenValue = Long.MIN_VALUE; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - assetAccountDev.toStringUtf8(), fakeTokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - String tokenId = Long.toString(-1); - long tokenValue = 0; - long callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 0; - callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(1000000); - tokenValue = 0; - callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountDev, blockingStubFull); - Long userAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountUser, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info( - "after dev has AssetId: " + assetAccountDev.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - logger.info( - "after user has AssetId: " + assetAccountDev.toStringUtf8() + ", userAssetCountAfter: " - + userAssetCountAfter); - - Assert.assertEquals(devAssetCountBefore, devAssetCountAfter); - Assert.assertEquals(userAssetCountBefore, userAssetCountAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java deleted file mode 100644 index cff6e0ddcae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java +++ /dev/null @@ -1,422 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken005 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - @Test(enabled = true, description = "TriggerContract with exception condition") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken005.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + transferAssetBefore); - - Long userAssetId = PublicMethed - .getAssetIssueValue(user001Address, ByteString.copyFromUtf8(tokenId), blockingStubFull); - logger.info("before userAssetId has AssetId " + tokenId + ", Count is " + userAssetId); - - // not such tokenId - tokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100000); - tokenValue = 10; - callValue = 5; - - GrpcAPI.Return response = PublicMethed - .triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, - tokenValue, user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // not have this tokenId - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Owner no asset!".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is Long.MAX_VALUE - tokenId = Long.toString(Long.MAX_VALUE); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - Assert.assertTrue(PublicMethed - .transferAsset(user001Address, assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenValue is not enough - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 100; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance is not sufficient.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenvalue is less than 0 - tokenId = assetAccountId.toStringUtf8(); - tokenValue = -1; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = Long.MIN_VALUE; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - /*PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - // tokenId is 100_0000 - tokenId = Long.toString(100_0000); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is long.min - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is 0 - tokenId = Long.toString(0); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : invalid arguments with tokenValue = 10, tokenId = 0" - .toLowerCase(), response.getMessage().toStringUtf8().toLowerCase()); - - /*PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - - tokenId = Long.toString(-1); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - - tokenId = Long.toString(100_0000L); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java deleted file mode 100644 index f39b96cdf00..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java +++ /dev/null @@ -1,476 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken011 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with correct value, deploy transfer contract") - public void test01DeployTransferTokenContract001() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 15048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 14048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount = PublicMethed - .queryAccount(dev001Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken011.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 200, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - /*Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - } - - - @Test(enabled = true, description = "TransferToken with correct value, deploy receive contract") - public void test02DeployRevContract002() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken011.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - final String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with correct value, transfer to a contract") - public void test03TriggerContract003() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - TransactionInfo transactionInfo = infoById.get(); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - - } - - @Test(enabled = true, description = "TransferToken with correct value, get contract tokenBalance") - public void test04TriggerTokenBalanceContract004() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev energy limit is " + devEnergyLimitBefore); - logger.info("before trigger, dev energy usage is " + devEnergyUsageBefore); - logger.info("before trigger, dev balance is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("before trigger, user energy limit is " + userEnergyLimitBefore); - logger.info("before trigger, user energy usage is " + userEnergyUsageBefore); - logger.info("before trigger, user balance is " + userBalanceBefore); - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Long triggerResult = ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray()); - logger.info("the receivercontract token by trigger contract: " + triggerResult); - Long assetIssueCount = PublicMethed - .getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertTrue(assetIssueCount == triggerResult); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java deleted file mode 100644 index 14ad0553a11..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken012 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy transfer contract with correct value") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 15048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 14048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken012.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 200, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - /*Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - } - - - @Test(description = "TransferToken with correct value, transfer to a normal account") - public void test02TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - logger.info("before trigger, receiveTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - } - - @Test(description = "TransferToken with correct value, get account tokenBalance") - public void test03TriggerTokenBalanceContract() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev energy limit is " + devEnergyLimitBefore); - logger.info("before trigger, dev energy usage is " + devEnergyUsageBefore); - logger.info("before trigger, dev balance is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("before trigger, user energy limit is " + userEnergyLimitBefore); - logger.info("before trigger, user energy usage is " + userEnergyUsageBefore); - logger.info("before trigger, user balance is " + userBalanceBefore); - - String param = "\"" + Base58.encode58Check(dev001Address) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - Long assetAccountCount = ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray()); - logger.info("the receivercontract token from contract: " + assetAccountCount); - Long assetIssueCount = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertEquals(assetIssueCount, assetAccountCount); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - // unfreeze resource - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java deleted file mode 100644 index 1134d4bae4c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java +++ /dev/null @@ -1,544 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken014 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //dev Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, - 1, 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //user Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(user001Address, tokenName, TotalSupply, - 1, 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountUser = PublicMethed.queryAccount( - user001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - assetAccountId = PublicMethed.queryAccount( - dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountId token name: " + tokenName); - logger.info("The assetAccountId token ID: " + assetAccountId.toStringUtf8()); - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken014.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " deploy receiver contract") - public void test02DeployRevContract() { - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken014.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " transfer to contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - - // transfer a not exist TokenId, to a contract - String tokenId = assetAccountUser.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // transfer a not exist TokenId, to a normal account - tokenId = assetAccountUser.toStringUtf8(); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is not enough - tokenId = assetAccountId.toStringUtf8(); - tokenValue = transferAssetBefore + 100; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // tokenValue is not enough, transfer to a normal account - tokenId = assetAccountId.toStringUtf8(); - tokenValue = transferAssetBefore + 100; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // TokenId is long.max, to a contract - String fackTokenId = Long.toString(Long.MAX_VALUE); - Long fakeValue = 1L; - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // TokenId is not exist, to a contract - fackTokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 10000); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // TokenId is long.max, to a normal account - fackTokenId = Long.toString(Long.MAX_VALUE); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // TokenId is not exist, to a normal account - fackTokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 10000); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is long.min, transfer to a contract - tokenId = assetAccountId.toStringUtf8(); - tokenValue = Long.MIN_VALUE; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("endowment out of long range", - infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is long.min, transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("endowment out of long range", - infoById.get().getResMessage().toStringUtf8()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Long devAssetAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetBefore, receiveAssetAfter); - Assert.assertEquals(devAssetBefore, devAssetAfter); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java deleted file mode 100644 index 07f96d21425..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java +++ /dev/null @@ -1,286 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.SUCESS; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken018 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] receiveTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] tmpAddress = ecKey3.getAddress(); - private String tmp001Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Transfer token to an inactive account") - public void testDeployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken023.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 0, - 10000, assetAccountId.toStringUtf8(), 200, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Delpoy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - /*Assert.assertFalse(PublicMethed - .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .transferAsset(user001Address, assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed - .getAssetIssueValue(tmpAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, receiveTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + receiveAssetBefore); - - String param = - "\"" + Base58.encode58Check(tmpAddress) + "\"," + assetAccountId.toStringUtf8() + ",\"1\""; - - final String triggerTxid = PublicMethed - .triggerContract(transferTokenContractAddress, "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - logger.info("infoById.get().getResMessage().toStringUtf8(): " + infoById.get().getResMessage() - .toStringUtf8()); - /*Assert.assertEquals( - "transfer trc10 failed: Validate InternalTransfer error, no ToAccount. " - + "And not allowed to create account in smart contract.", - infoById.get().getResMessage().toStringUtf8());*/ - - Long transferAssetAfter = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "after trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed - .getAssetIssueValue(tmpAddress, assetAccountId, blockingStubFull); - logger.info( - "after trigger, receiveTokenAddress has AssetId " + assetAccountId.toStringUtf8() - + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, Long.valueOf(receiveAssetBefore + 1)); - Assert.assertEquals(transferAssetBefore, Long.valueOf(transferAssetAfter - 1)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java deleted file mode 100644 index c78a088dd3c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java +++ /dev/null @@ -1,235 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken023 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] transferTokenContractAddress; - byte[] btestAddress; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "deploy contract for transfer token") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 4048000000L, fromAddress, testKey002, blockingStubFull)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - int i = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath2 = "src/test/resources/soliditycode/contractTrcToken023.sol"; - String contractName2 = "tokenTest"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath2, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert - .assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert - .assertFalse(PublicMethed.sendcoin(btestAddress, 1000000000L, fromAddress, - testKey002, blockingStubFull));*/ - - // devAddress transfer token to userAddress - PublicMethed.transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), - 100, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "transfer token which from address does not have") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId,blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId,blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed.getAssetIssueValue(btestAddress, - assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = "\"" + Base58.encode58Check(btestAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java deleted file mode 100644 index cc6251d9720..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java +++ /dev/null @@ -1,514 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken026 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] btestAddress; - byte[] ctestAddress; - byte[] transferTokenContractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferToken contract") - public void deploy01TransferTokenContract001() { - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken026.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - ctestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - - String contractName2 = "token"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "Multistage call transferToken use right tokenID") - public void deploy02TransferTokenContract002() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueCAddress:" + beforeAssetIssueCAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - // 1.user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - Assert.assertTrue(afterAssetIssueCAddress == beforeAssetIssueCAddress - 1); - } - - @Test(enabled = true, description = "Multistage call transferToken use fake tokenID") - public void deploy03TransferTokenContract003() { - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - //3. user trigger A to transfer token to B - int i = randomInt(6666666, 9999999); - - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - - String param1 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + tokenId1 - .toStringUtf8() - + "\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param1, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress1:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress, afterBalanceContractAddress1); - Assert.assertTrue(afterAssetIssueContractAddress == afterAssetIssueContractAddress1); - Assert.assertTrue(afterAssetIssueBAddress == afterAssetIssueBAddress1); - Assert.assertTrue(afterAssetIssueCAddress == afterAssetIssueCAddress1); - } - - @Test(enabled = true, description = "Multistage call transferToken token value not enough") - public void deploy04TransferTokenContract004() { - - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress1 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress1); - - //4. user trigger A to transfer token to B - String param2 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",10000000,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid2 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param2, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress2 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueBAddress2:" + afterAssetIssueBAddress2); - logger.info("afterAssetIssueCAddress2:" + afterAssetIssueCAddress2); - logger.info("afterBalanceContractAddress2:" + afterBalanceContractAddress2); - - Assert.assertEquals(afterBalanceContractAddress1, afterBalanceContractAddress2); - Assert.assertTrue(afterAssetIssueContractAddress1 == afterAssetIssueContractAddress2); - Assert.assertTrue(afterAssetIssueBAddress1 == afterAssetIssueBAddress2); - Assert.assertTrue(afterAssetIssueCAddress1 == afterAssetIssueCAddress2); - } - - @Test(enabled = true, description = "Multistage call transferToken calltoken ID not exist") - public void deploy05TransferTokenContract005() { - - final Long afterAssetIssueContractAddress2 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress2 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //5. user trigger A to transfer token to B - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - int i = randomInt(6666666, 9999999); - - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - final String triggerTxid3 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param3, false, 0, 1000000000L, tokenId1 - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid3 == null); - - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress3 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress3 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount3:" + afterAssetIssueDevAddress3); - logger.info("afterAssetIssueDevAddress3:" + afterAssetIssueContractAddress3); - logger.info("afterAssetIssueBAddress3:" + afterAssetIssueBAddress3); - logger.info("afterAssetIssueCAddress3:" + afterAssetIssueCAddress3); - logger.info("afterBalanceContractAddress3:" + afterBalanceContractAddress3); - - Assert.assertEquals(afterBalanceContractAddress2, afterBalanceContractAddress3); - Assert.assertTrue(afterAssetIssueContractAddress2 == afterAssetIssueContractAddress3); - Assert.assertTrue(afterAssetIssueBAddress2 == afterAssetIssueBAddress3); - Assert.assertTrue(afterAssetIssueCAddress2 == afterAssetIssueCAddress3); - } - - @Test(enabled = true, description = "Multistage call transferToken calltoken value not enough") - public void deploy06TransferTokenContract006() { - - final Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress3 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //6. user trigger A to transfer token to B - String param4 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid4 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param4, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 100000000, dev001Address, dev001Key, blockingStubFull); - Assert.assertTrue(triggerTxid4 == null); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress4 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress4:" + afterAssetIssueContractAddress4); - logger.info("afterAssetIssueBAddress4:" + afterAssetIssueBAddress4); - logger.info("afterAssetIssueCAddress4:" + afterAssetIssueCAddress4); - logger.info("afterBalanceContractAddress4:" + afterBalanceContractAddress4); - - Assert.assertEquals(afterBalanceContractAddress3, afterBalanceContractAddress4); - Assert.assertTrue(afterAssetIssueContractAddress3 == afterAssetIssueContractAddress4); - Assert.assertTrue(afterAssetIssueBAddress3 == afterAssetIssueBAddress4); - Assert.assertTrue(afterAssetIssueCAddress3 == afterAssetIssueCAddress4); - } - - @Test(enabled = true, description = "Multistage call transferToken use right tokenID,tokenvalue") - public void deploy07TransferTokenContract007() { - final Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress4 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress4 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //2. user trigger A to transfer token to B - String param5 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid5 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param5, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueContractAddress5 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress5 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress5 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress5 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress5:" + afterAssetIssueContractAddress5); - logger.info("afterAssetIssueBAddress5:" + afterAssetIssueBAddress5); - logger.info("afterAssetIssueCAddress5:" + afterAssetIssueCAddress5); - logger.info("afterBalanceContractAddress5:" + afterBalanceContractAddress5); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress4, afterBalanceContractAddress5); - Assert.assertTrue(afterAssetIssueContractAddress4 + 2 == afterAssetIssueContractAddress5); - Assert.assertTrue(afterAssetIssueBAddress4 == afterAssetIssueBAddress5); - Assert.assertTrue(afterAssetIssueCAddress4 - 1 == afterAssetIssueCAddress5); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java deleted file mode 100644 index 63fc4690a95..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java +++ /dev/null @@ -1,490 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken027 { - - - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] btestAddress; - byte[] ctestAddress; - byte[] transferTokenContractAddress; - int i1 = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i1)); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - /** - * constructor. - */ - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferToken contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken027.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - ctestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - - - String contractName2 = "token"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull));*/ - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use right tokenID") - public void deploy02TransferTokenContract() { - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueCAddress:" + beforeAssetIssueCAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - // 1.user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - Assert.assertTrue(afterAssetIssueCAddress == beforeAssetIssueCAddress - 1); - - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use fake tokenID") - public void deploy03TransferTokenContract() { - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - String param1 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + tokenId1.toStringUtf8() + "\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param1, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress1:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - - - Assert.assertEquals(afterBalanceContractAddress, afterBalanceContractAddress1); - Assert.assertTrue(afterAssetIssueContractAddress == afterAssetIssueContractAddress1); - Assert.assertTrue(afterAssetIssueBAddress == afterAssetIssueBAddress1); - Assert.assertTrue(afterAssetIssueCAddress == afterAssetIssueCAddress1); - } - - - @Test(enabled = true, description = "Multistage delegatecall transferToken token value" - + " not enough") - public void deploy04TransferTokenContract() { - - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress1 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param2 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",10000000,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid2 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param2, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress2 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount2:" + afterAssetIssueDevAddress2); - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueBAddress2:" + afterAssetIssueBAddress2); - logger.info("afterAssetIssueCAddress2:" + afterAssetIssueCAddress2); - logger.info("afterBalanceContractAddress2:" + afterBalanceContractAddress2); - - Assert.assertEquals(afterBalanceContractAddress1, afterBalanceContractAddress2); - Assert.assertTrue(afterAssetIssueContractAddress1 == afterAssetIssueContractAddress2); - Assert.assertTrue(afterAssetIssueBAddress1 == afterAssetIssueBAddress2); - Assert.assertTrue(afterAssetIssueCAddress1 == afterAssetIssueCAddress2); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken calltoken ID" - + " not exist") - public void deploy05TransferTokenContract() { - - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress2 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid3 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param3, false, 0, 1000000000L, tokenId1.toStringUtf8(), - 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid3 == null); - - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress3 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount3:" + afterAssetIssueDevAddress3); - logger.info("afterAssetIssueDevAddress3:" + afterAssetIssueContractAddress3); - logger.info("afterAssetIssueBAddress3:" + afterAssetIssueBAddress3); - logger.info("afterAssetIssueCAddress3:" + afterAssetIssueCAddress3); - logger.info("afterBalanceContractAddress3:" + afterBalanceContractAddress3); - - Assert.assertEquals(afterBalanceContractAddress2, afterBalanceContractAddress3); - Assert.assertTrue(afterAssetIssueContractAddress2 == afterAssetIssueContractAddress3); - Assert.assertTrue(afterAssetIssueBAddress2 == afterAssetIssueBAddress3); - Assert.assertTrue(afterAssetIssueCAddress2 == afterAssetIssueCAddress3); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken calltoken value " - + "not enough") - public void deploy06TransferTokenContract() { - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress3 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param4 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid4 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param4, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 100000000, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid4 == null); - Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress4 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - Long afterUserBalance4 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("afterAssetIssueCount4:" + afterAssetIssueDevAddress4); - logger.info("afterAssetIssueDevAddress4:" + afterAssetIssueContractAddress4); - logger.info("afterAssetIssueBAddress4:" + afterAssetIssueBAddress4); - logger.info("afterAssetIssueCAddress4:" + afterAssetIssueCAddress4); - logger.info("afterBalanceContractAddress4:" + afterBalanceContractAddress4); - logger.info("afterUserBalance4:" + afterUserBalance4); - - Assert.assertEquals(afterBalanceContractAddress3, afterBalanceContractAddress4); - Assert.assertTrue(afterAssetIssueContractAddress3 == afterAssetIssueContractAddress4); - Assert.assertTrue(afterAssetIssueBAddress3 == afterAssetIssueBAddress4); - Assert.assertTrue(afterAssetIssueCAddress3 == afterAssetIssueCAddress4); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use right tokenID," - + "tokenvalue") - public void deploy07TransferTokenContract() { - final Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress4 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param5 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid5 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param5, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress5 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress5 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress5 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress5 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress5 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount5:" + afterAssetIssueDevAddress5); - logger.info("afterAssetIssueDevAddress5:" + afterAssetIssueContractAddress5); - logger.info("afterAssetIssueBAddress5:" + afterAssetIssueBAddress5); - logger.info("afterAssetIssueCAddress5:" + afterAssetIssueCAddress5); - logger.info("afterBalanceContractAddress5:" + afterBalanceContractAddress5); - - Assert.assertEquals(afterBalanceContractAddress4, afterBalanceContractAddress5); - Assert.assertTrue(afterAssetIssueContractAddress4 + 2 == afterAssetIssueContractAddress5); - Assert.assertTrue(afterAssetIssueBAddress4 == afterAssetIssueBAddress5); - Assert.assertTrue(afterAssetIssueCAddress4 - 1 == afterAssetIssueCAddress5); - Assert.assertTrue(afterAssetIssueDevAddress4 - 1 == afterAssetIssueDevAddress5); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java deleted file mode 100644 index 06ddba41e0e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken028 { - - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - int i1 = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i1)); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy tokenBalanceWithSameName contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 3, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken028.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - - @Test(enabled = true, description = "Trigger tokenBalanceWithSameName") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - String param = - "\"" + tokenId1 - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "tokenBalanceWithSameName(trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - Long afterUserBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - logger.info("afterUserBalance:" + afterUserBalance); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - - String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "getA()", - "#", false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(triggerTxid1, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(returnnumber1 == 9); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java deleted file mode 100644 index 5dc1e876212..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken029 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferTokenwithSameName contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.printAddress(dev001Key); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken029.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, - 1000000000L, fromAddress, testKey002, blockingStubFull));*/ - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Trigger transferTokenwithSameName") - public void deploy02TransferTokenContract() { - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - // user trigger A to transfer token to B - ByteString assetAccountDev = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - ByteString fakeTokenId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountDev.toStringUtf8()) + 100)); - String param = "\"" + fakeTokenId.toStringUtf8() + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenWithSameName(trcToken,uint256)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueCount:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java deleted file mode 100644 index c35993a0207..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java +++ /dev/null @@ -1,187 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken030 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy suicide contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken030.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger suicide contract,toaddress is other") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - final Long beforeUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(user001Address) - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "kill(address)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - final Long afterUserBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertTrue(afterBalanceContractAddress == 0); - Assert.assertTrue(beforeAssetIssueUserAddress + beforeAssetIssueContractAddress - == afterAssetIssueUserAddress); - Assert.assertTrue(beforeUserBalance + beforeBalanceContractAddress - == afterUserBalance); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java deleted file mode 100644 index 4622e1f4897..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken031 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy suicide contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("assetId: " + assetAccountId); - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken031.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(transferTokenContractAddress); - - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, - 1000000000L, fromAddress, testKey002, blockingStubFull));*/ - } - - @Test(enabled = true, description = "Trigger suicide contract,toaddress is myself") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(transferTokenContractAddress) - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "kill(address)", param, false, 0, 1000000000L, - "0", 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Assert.assertTrue(afterBalanceContractAddress == 0); - Assert.assertTrue(afterAssetIssueContractAddress == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java deleted file mode 100644 index f9e5ed01772..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken034 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(enabled = true, description = "Deploy after transfertoken execute require contract") - public void deploy01TransferTokenContract() { - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken034.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 100000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 50, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "Trigger after transfertoken execute require contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(user001Address) + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "failTransferTokenRevert(address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - - Assert.assertEquals(beforeAssetIssueDevAddress, afterAssetIssueDevAddress); - Assert.assertEquals(beforeAssetIssueUserAddress, afterAssetIssueUserAddress); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java deleted file mode 100644 index e3568c6873c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken035 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy after transfertoken execute assert contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 9999000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken035.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 100000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 50, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger after transfertoken execute assert contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(user001Address) + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "failTransferTokenError(address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - - Assert.assertEquals(beforeAssetIssueDevAddress, afterAssetIssueDevAddress); - Assert.assertEquals(beforeAssetIssueUserAddress, afterAssetIssueUserAddress); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java deleted file mode 100644 index 400e51cae3a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java +++ /dev/null @@ -1,527 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken036 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] transferTokenContractAddress; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - int originEnergyLimit = 50000; - byte[] transferTokenWithPureTestAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = false, description = "Deploy contract") - public void deploy01TransferTokenContract() { - - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 9999000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - // String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - // String contractName = "IllegalDecorate"; - // HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - // String code = retMap.get("byteCode").toString(); - // String abi = retMap.get("abI").toString(); - // transferTokenContractAddress = PublicMethed - // .deployContract(contractName, abi, code, "", maxFeeLimit, - // 0L, 0, originEnergyLimit, "0", - // 0, null, dev001Key, dev001Address, - // blockingStubFull); - - - // - // // devAddress transfer token to userAddress - // PublicMethed - // .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100, - // dev001Address, - // dev001Key, - // blockingStubFull); - // Assert - // .assertTrue(PublicMethed.sendcoin(transferTokenContractAddress, 100, fromAddress, - // testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Trigger transferTokenWithPure contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenWithPure(address,uint256)", - param, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterContractAddressBalance:" + afteruser001AddressAddressBalance); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(beforeAssetIssueDevAddress - 10 == afterAssetIssueDevAddress); - Assert.assertTrue(beforeAssetIssueUserAddress + 10 == afterAssetIssueUserAddress); - Assert.assertTrue(user001AddressAddressBalance + 10 == afteruser001AddressAddressBalance); - - String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName1 = "IllegalDecorate1"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - transferTokenWithPureTestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed - .transferAsset(transferTokenWithPureTestAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithPureTestAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Trigger transferTokenWithConstant contract") - public void deploy03TransferTokenContract() { - Account info1; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - Long beforeAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance1 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance1); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed1); - logger.info("beforeNetUsed:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed1); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress1); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress1); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress1); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance1); - - // user trigger A to transfer token to B - String param1 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenWithPureTestAddress, - "transferTokenWithConstant(address,uint256)", - param1, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance1 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress1); - logger.info("afterContractAddressBalance:" + afteruser001AddressAddressBalance1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertEquals(beforeBalance1, afterBalance1); - Assert.assertEquals(beforeAssetIssueDevAddress1, afterAssetIssueDevAddress1); - Assert.assertEquals(beforeAssetIssueUserAddress1, afterAssetIssueUserAddress1); - Assert.assertEquals(user001AddressAddressBalance1, afteruser001AddressAddressBalance1); - } - - @Test(enabled = false, description = "Trigger transferTokenWithView contract") - public void deploy04TransferTokenContract() { - String filePath2 = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName2 = "IllegalDecorate2"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] transferTokenWithViewAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed - .transferAsset(transferTokenWithViewAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithViewAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info2; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info2 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - Long beforeAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress2 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenWithViewAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance2 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueContractAddress2:" + beforeAssetIssueContractAddress2); - logger.info("beforeAssetIssueDevAddress2:" + beforeAssetIssueDevAddress2); - logger.info("beforeAssetIssueUserAddress2:" + beforeAssetIssueUserAddress2); - logger.info("user001AddressAddressBalance2:" + user001AddressAddressBalance2); - - // user trigger A to transfer token to B - String param2 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - String triggerTxid2 = PublicMethed.triggerContract(transferTokenWithViewAddress, - "transferTokenWithView(address,uint256)", - param2, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - - Account infoafter2 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenWithViewAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress2 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance2 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueDevAddress2); - logger.info("afterAssetIssueContractAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueUserAddress2:" + afterAssetIssueUserAddress2); - logger.info("afteruser001AddressAddressBalance2:" + afteruser001AddressAddressBalance2); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - - Assert.assertEquals(beforeAssetIssueDevAddress2, afterAssetIssueDevAddress2); - Assert.assertEquals(beforeAssetIssueUserAddress2, afterAssetIssueUserAddress2); - Assert.assertEquals(user001AddressAddressBalance2, afteruser001AddressAddressBalance2); - } - - @Test(enabled = false, description = "Trigger transferTokenWithNoPayable contract") - public void deploy05TransferTokenContract() { - String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName3 = "IllegalDecorate3"; - HashMap retMap3 = PublicMethed.getBycodeAbi(filePath, contractName3); - - String code3 = retMap3.get("byteCode").toString(); - String abi3 = retMap3.get("abI").toString(); - byte[] transferTokenWithOutPayableTestAddress = PublicMethed - .deployContract(contractName3, abi3, code3, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed - .transferAsset(transferTokenWithOutPayableTestAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithOutPayableTestAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info3; - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info3 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - Long beforeAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress3 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue( - transferTokenWithOutPayableTestAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance3 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance3); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed3); - logger.info("beforeNetUsed:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed3); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress3); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress3); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress3); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance3); - - String param3 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - String triggerTxid3 = PublicMethed.triggerContract(transferTokenWithOutPayableTestAddress, - "transferTokenWithOutPayable(address,uint256)", - param3, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter3 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue( - transferTokenWithOutPayableTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress3 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance3 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 1); - - Assert.assertEquals(beforeAssetIssueDevAddress3, afterAssetIssueDevAddress3); - Assert.assertEquals(beforeAssetIssueUserAddress3, afterAssetIssueUserAddress3); - Assert.assertEquals(user001AddressAddressBalance3, afteruser001AddressAddressBalance3); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - null, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - null, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java deleted file mode 100644 index 14c395b2f2f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken037 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Multi-level call transferToken tokenBalance") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken037.sol"; - String contractName = "receiveTrc10"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 0, originEnergyLimit, "0", 0, - null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "transferTrc10"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(btestAddress) + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "receive(address)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 10, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueDevAddress == beforeAssetIssueDevAddress - 10); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress + 10); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java deleted file mode 100644 index af4cc453903..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java +++ /dev/null @@ -1,209 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken038 { - - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Multi-level call transferToken assert tokenBalance ") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 3, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertFalse(assetAccountId.toStringUtf8().equals("")); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken038.sol"; - String contractName2 = "transferTrc10"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - final byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - String contractName = "receiveTrc10"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull)); - Assert.assertFalse(PublicMethed.sendcoin(btestAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull));*/ - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(btestAddress) + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "receive(address)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, null, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java deleted file mode 100644 index 9f18bb1afb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java +++ /dev/null @@ -1,345 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken039 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] proxyTestAddress; - byte[] atestAddress; - byte[] btestAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy Proxy contract") - public void deploy01TransferTokenContract() { - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info("user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken039.sol"; - String contractName = "Proxy"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - proxyTestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 1000, null, dev001Key, dev001Address, - blockingStubFull); - - String contractName1 = "A"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - atestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "B"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, dependsOnMethods = "deploy01TransferTokenContract", - description = "Trigger Proxy contract use AddressA") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueAAddress = PublicMethed - .getAssetIssueValue(atestAddress, assetAccountId, - blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long beforeUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeBalance:" + beforeBalance); - - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(atestAddress) + "\""; - String param1 = - "\"" + "1" + "\",\"" + Base58.encode58Check(user001Address) + "\",\"" + assetAccountId - .toStringUtf8() - + "\""; - - String triggerTxid = PublicMethed.triggerContract(proxyTestAddress, - "upgradeTo(address)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String triggerTxid1 = PublicMethed.triggerContract(proxyTestAddress, - "trans(uint256,address,trcToken)", - param1, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), - 1, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueAAddress = PublicMethed - .getAssetIssueValue(atestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long afterUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - logger.info("afterUserBalance:" + afterUserBalance); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterAssetIssueUserAddress == beforeAssetIssueUserAddress); - Assert.assertTrue(afterBalanceContractAddress == beforeBalanceContractAddress - 1); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueDevAddress == beforeAssetIssueDevAddress - 1); - Assert.assertTrue(afterUserBalance == beforeUserBalance + 1); - Assert.assertTrue(afterAssetIssueUserAddress == afterAssetIssueUserAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - } - - @Test(enabled = true,dependsOnMethods = "deploy02TransferTokenContract", - description = "Trigger Proxy contract use AddressB") - public void deploy03TransferTokenContract() { - Account info1; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - - Long beforeBalanceContractAddress1 = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long beforeUserBalance1 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeAssetIssueContractAddress1:" + beforeAssetIssueContractAddress1); - logger.info("beforeAssetIssueBAddress1:" + beforeAssetIssueBAddress1); - - logger.info("beforeAssetIssueDevAddress1:" + beforeAssetIssueDevAddress1); - logger.info("beforeAssetIssueUserAddress1:" + beforeAssetIssueUserAddress1); - logger.info("beforeBalanceContractAddress1:" + beforeBalanceContractAddress1); - logger.info("beforeUserBalance1:" + beforeUserBalance1); - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\""; - String param2 = - "\"" + "1" + "\",\"" + Base58.encode58Check(user001Address) + "\",\"" + assetAccountId - .toStringUtf8() - + "\""; - - String triggerTxid2 = PublicMethed.triggerContract(proxyTestAddress, - "upgradeTo(address)", param3, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - String triggerTxid3 = PublicMethed.triggerContract(proxyTestAddress, - "trans(uint256,address,trcToken)", - param2, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), - 1, dev001Address, dev001Key, - blockingStubFull); - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - - Long afterAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long afterUserBalance1 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueUserAddress1:" + afterAssetIssueUserAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - logger.info("afterUserBalance1:" + afterUserBalance1); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertTrue(afterAssetIssueUserAddress1 == beforeAssetIssueUserAddress1); - Assert.assertTrue(afterBalanceContractAddress1 == beforeBalanceContractAddress1 - 1); - Assert.assertTrue(afterAssetIssueContractAddress1 == beforeAssetIssueContractAddress1 + 1); - Assert.assertTrue(afterAssetIssueDevAddress1 == beforeAssetIssueDevAddress1 - 1); - Assert.assertTrue(afterUserBalance1 == beforeUserBalance1 + 1); - Assert.assertTrue(afterAssetIssueUserAddress1 == afterAssetIssueUserAddress1); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java deleted file mode 100644 index 9281c03d8cc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken041 { - - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Trigger contract msg.tokenId add 1,msg.tokenValue add 1") - public void deployTransferTokenContract() { - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // freeze balance - PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull); - - PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - final ByteString fakeTokenId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100)); - - // deploy transferTokenContract - String filePath = "src/test/resources/soliditycode/contractTrcToken041.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + fakeTokenId - .toStringUtf8() - + "\",\"105\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, fakeTokenId.toStringUtf8(), - 10000000L, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertTrue(afterEnergyUsed == 0L); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java deleted file mode 100644 index c07017f0ce5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java +++ /dev/null @@ -1,466 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken043 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] user002Address = ecKey3.getAddress(); - private String user002Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - @Test(enabled = true, description = "TransferToken with invalid tokenId, deploy transferContract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user002Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken043.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with invalid tokenId, deploy receive contract") - public void test02DeployRevContract() { - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken043.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with invalid tokenId, transferToken") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user002Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - // tokenId is 100_0000 - String tokenId = Long.toString(100_0000); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Triger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenId is -1 - tokenId = Long.toString(-1); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("validateForSmartContract failure, not valid token id", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenId is long.min - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - // tokenId is 0, contract not have trx - tokenId = Long.toString(0); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - Assert.assertFalse(PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user002Address, 5000000, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //tokenId is 0, transfer contract has trx, transfer to normal account - tokenId = Long.toString(0); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(1); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user002Address, user002Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenid bigger than long.max, trigger to a contract - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestIDOverBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user002Address, user002Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, receiveAssetBefore); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - - // unfreeze resource - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user002Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java deleted file mode 100644 index ef74ef6e0c3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java +++ /dev/null @@ -1,193 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken048 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken msg.value msg,tokenvalue is negative number") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - final ByteString fakeassetAccountId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100)); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken048.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testMsgTokenValue()", - "#", false, 0, 100000000L, fakeassetAccountId.toStringUtf8(), - -1000, user001Address, user001Key, blockingStubFull); - - String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testMsgValue()", - "#", false, -1000, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java deleted file mode 100644 index 0ee8fe250c5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java +++ /dev/null @@ -1,228 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken049 { - - - private static final long TotalSupply = 10000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - /** - * constructor. - */ - - public ByteString createAssetissue(byte[] devAddress, String devKey, String tokenName) { - - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - logger.info("The token name: " + tokenName); - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(devAddress, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, devKey, blockingStubFull)); - - ByteString assetAccountId = PublicMethed.queryAccount(devAddress, blockingStubFull) - .getAssetIssuedID(); - logger.info("The tokenID: " + assetAccountId); - - return assetAccountId; - } - - @Test(enabled = true, description = "TransferToken to myself") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - ByteString tokenId = createAssetissue(user001Address, user001Key, tokenName); - - PublicMethed.transferAsset(dev001Address, tokenId.toByteArray(), 101, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken049.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, tokenId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - byte[] transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - - Long beforeBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = - PublicMethed.getAssetIssueValue(user001Address, tokenId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, tokenId, blockingStubFull); - final Long beforeAssetIssueDev = PublicMethed.getAssetIssueValue(dev001Address, tokenId, - blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId - .toStringUtf8() - + "\",\"1\""; - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = - PublicMethed.getAssetIssueValue(user001Address, tokenId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, tokenId, blockingStubFull); - final Long afterAssetIssueDev = PublicMethed.getAssetIssueValue(dev001Address, tokenId, - blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertTrue(beforeAssetIssueContractAddress == afterAssetIssueContractAddress); - - Assert.assertTrue(beforeAssetIssueDev == afterAssetIssueDev); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java deleted file mode 100644 index f428d2932a7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken050 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract address ") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken050.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] transferTokenContractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - final Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(transferTokenContractAddress) + "\",\"" + assetAccountId - .toStringUtf8() - + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertTrue(beforeAssetIssueContractAddress == afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java deleted file mode 100644 index 5abad4b440d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken051 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract developer tokenID is 0") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 6048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken051.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - - String fakeassetAccountId = Long.toString(0L); - - String param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeassetAccountId + ",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertFalse(infoById.get().getResultValue() == 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java deleted file mode 100644 index b0b5efc8f20..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken052 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract address tokenID is 0") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 6048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken052.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long beforetransferTokenContractAddressBalance = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - final Long beforeDevBalance = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - String fakeassetAccountId = Long.toString(0L); - - String param = "\"" + Base58.encode58Check(transferTokenContractAddress) - + "\"," + fakeassetAccountId + ",\"1\""; - // user trigger A to transfer token to B - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long aftertransferTokenContractAddressBalance = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - final Long afterDevBalance = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getBalance(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals( - beforetransferTokenContractAddressBalance, aftertransferTokenContractAddressBalance); - Assert.assertEquals(beforeDevBalance, afterDevBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - - - @AfterClass - public void shutdown() throws InterruptedException { - - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java deleted file mode 100644 index 9ad9496fae4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java +++ /dev/null @@ -1,272 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken054 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Trigger transferToken with 0 tokenValue") - public void testTriggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - //String contractName = "transferTokenContract"; - - String filePath = "./src/test/resources/soliditycode/contractTrcToken054.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 0; - callValue = 5; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info( - "the value: " + PublicMethed.getStrings(infoById.get().getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java deleted file mode 100644 index 36ce5677f1d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken055 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger TransferToken with long.max tokenId," - + " and 0tokenValue") - public void triggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken055.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - tokenId = Long.toString(Long.MAX_VALUE); - tokenValue = 0; - callValue = 5; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info( - "the value: " + PublicMethed.getStrings(infoById.get().getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java deleted file mode 100644 index 4884706c2bf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java +++ /dev/null @@ -1,232 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken060 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken060.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 0; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray())); - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java deleted file mode 100644 index c13556767f7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken061 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue and long.max tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken061.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = Long.toString(Long.MAX_VALUE); - long tokenValue = 0; - long callValue = 10; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray())); - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java deleted file mode 100644 index a7bce360148..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java +++ /dev/null @@ -1,450 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken064 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(user001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountUser = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken064.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, deploy receiver contract") - public void test02DeployRevContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken064.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, trigger contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - Long callValue = Long.valueOf(0); - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValue0IdBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getResMessage().toStringUtf8()); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - //Assert.assertEquals("BigInteger out of long range", - infoById.get().getResMessage().toStringUtf8()); - - //transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) + "\""; - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValue0IdBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("BigInteger out of long range", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - String tokenId = Long.toString(Long.MIN_VALUE); - Long tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(100_0000); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(-1); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(0); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValueMaxLong(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValueMaxLong(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, receiveAssetBefore); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java deleted file mode 100644 index 5fef9eca4ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java +++ /dev/null @@ -1,333 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken066 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, deploy transferContract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken066.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, deploy receive contract") - public void test02DeployRevContract() { - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken066.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, trigger transferContract") - public void test03TriggerContract() { - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(0); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - TransactionInfo transactionInfo = infoById.get(); - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - logger.info("the value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, get contract tokenBalance") - public void test04TriggerTokenBalanceContract() { - - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("the receivercontract token: " + ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray())); - Long assetIssueCount = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - - Assert.assertTrue(assetIssueCount == ByteArray - .toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java deleted file mode 100644 index 67d9f896944..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java +++ /dev/null @@ -1,339 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken067 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken067.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, deploy receive contract") - public void test02DeployRevContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken067.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, trigger transfer contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = Long.toString(Long.MAX_VALUE); - Long tokenValue = Long.valueOf(0); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info( - "the value: " + PublicMethed.getStrings(transactionInfo.getLogList().get(0).getData() - .toByteArray())); - - List retList = PublicMethed.getStrings(transactionInfo.getLogList().get(0) - .getData().toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, get tokenBalance") - public void test04TriggerTokenBalanceContract() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("the receivercontract token: " + ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray())); - Long assetIssueCount = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertTrue(assetIssueCount == ByteArray - .toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java deleted file mode 100644 index 1d8024559e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java +++ /dev/null @@ -1,260 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken073 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "TokenBalance with correct tokenValue and tokenId") - public void testTokenBalanceContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 11000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 300000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken073.sol"; - String contractName = "Dest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - tokenId = assetAccountId.toStringUtf8(); - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - Long msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - Long msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - Long msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(msgTokenBalance, devAssetBefore); - - tokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 1000); - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(Long.valueOf(0), msgTokenBalance); - - tokenId = Long.toString(Long.MAX_VALUE); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(Long.valueOf(0), msgTokenBalance); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java deleted file mode 100644 index 849f752489d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java +++ /dev/null @@ -1,268 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken075 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "TokenBalance with exception condition") - public void testTokenBalanceContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 11000_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken075.sol"; - String contractName = "Dest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - tokenId = Long.toString(100_0000); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(0); - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(-1); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(Long.MIN_VALUE); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenLongMin()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenLongMax()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("BigInteger out of long range", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java deleted file mode 100644 index 51f7fc1b2db..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken076 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Origin test ") - public void testDeployTransferTokenContract() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken076.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - - PublicMethed.triggerContract(contractAddress, - "test()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed.triggerContract(contractAddress, - "getResult1()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - logger.info("infoById:" + infoById); - Long returnnumber = ByteArray.toLong(ByteArray.fromHexString(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 1); - - txid = PublicMethed.triggerContract(contractAddress, - "getResult2()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - logger.info("-------------------------"); - - logger.info("infoById:" + infoById); - Long returnnumber2 = ByteArray.toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java deleted file mode 100644 index f5cfcdab3b6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java +++ /dev/null @@ -1,184 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken077 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = false) - public void testAddress001() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken077.sol"; - String contractName = "trcToken077"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - Optional deployInfo = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - contractAddress = deployInfo.get().getContractAddress().toByteArray(); - logger.info("Deploy energy is " + deployInfo.get().getReceipt().getEnergyUsageTotal()); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "addressTest()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - logger.info("Trigger energy is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - } - - @Test(enabled = true, description = "The value of address is not at the beginning of 41") - public void testAddress002() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "trcToken077"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5060b0806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080" - + "fd5b50d28015602757600080fd5b5060043610605c577c01000000000000000000000000000000000000000" - + "0000000000000000060003504636241c1d881146061575b600080fd5b60676079565b604080519182525190" - + "81900360200190f35b60405130908190529056fea165627a7a723058207b9b52e71420f2fa4cb55ffd55641" - + "355ec84e09d6d4545c629dde7cc01d74a100029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"addressTest\",\"outputs\":[{\"name" - + "\":\"addressValue\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonp" - + "ayable\",\"type\":\"function\"}]"; - - String deploytxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional deployById = PublicMethed - .getTransactionInfoById(deploytxid, blockingStubFull); - contractAddress = deployById.get().getContractAddress().toByteArray(); - logger.info("infoById:" + deployById); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "addressTest()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - - Assert.assertNotNull(infoById); - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - Assert.assertEquals(exceptedResult, ByteArray.toHexString(contractAddress)); - - } - - - /** - * constructor. - */ - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java deleted file mode 100644 index 84ace997b17..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java +++ /dev/null @@ -1,275 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractTrcToken078 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String priKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - /** - * constructor. - */ - - public static String byte2HexStr(byte[] b, int offset, int length) { - String stmp = ""; - StringBuilder sb = new StringBuilder(""); - for (int n = offset; n < offset + length && n < b.length; n++) { - stmp = Integer.toHexString(b[n] & 0xFF); - sb.append((stmp.length() == 1) ? "0" + stmp : stmp); - } - return sb.toString().toUpperCase().trim(); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Origin test call") - public void testOriginCall001() { - PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - String filePath1 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress1; - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - String filePath2 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - logger.info("infoById : " + infoById); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB2(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - logger.info("Trigger InfobyId: " + infoById2); - Account info1 = PublicMethed.queryAccount(internalTxsAddress, blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(internalTxsAddress, - blockingStubFull); - logger.info("getEnergyUsed " + resourceInfo1.getEnergyUsed()); - logger.info("getEnergyLimit " + resourceInfo1.getEnergyLimit()); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - - } - - @Test(enabled = true, description = "Origin test delegatecall") - public void testOriginDelegatecall001() { - PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - String filePath1 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress1; - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - String filePath2 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - logger.info("infoById : " + infoById2); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - - } - - private List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; - } - - /** - * constructor. - */ - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java deleted file mode 100644 index 46c5948b69b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java +++ /dev/null @@ -1,220 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken079 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Trigger transferToken with 0 tokenValue and tokenId") - public void triggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken079.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(0); - tokenValue = 0; - callValue = 5; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - logger.info("the value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java deleted file mode 100644 index c77fd323690..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken080 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue and tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken080.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 10; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - logger.info("The msg value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java deleted file mode 100644 index 8312b886b10..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java +++ /dev/null @@ -1,239 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken081 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] tokenReceiver = null; - private byte[] tokenSender = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken081.sol"; - String contractName = "TokenReceiver"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - - tokenReceiver = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed - .getContract(tokenReceiver, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - - contractName = "TokenSender"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - tokenSender = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, 10000L, assetAccountId.toStringUtf8(), - 10L, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(tokenSender, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId before: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Long devAssetCountAfterDeploy = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after deploy tokenSender AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfterDeploy); - Assert.assertTrue(10 == devAssetCountBefore - devAssetCountAfterDeploy); - Assert.assertTrue(10 == contractAssetCount); - - } - - - @Test(enabled = true, description = "transfer 1 trc10 to contract by assembly") - public void transferTokenToContract() { - Long senderAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("before trigger tokenSender has AssetId before: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountBefore); - - Long receiverAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenReceiver, assetAccountId, blockingStubFull); - logger.info("before trigger tokenReceiver AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + receiverAssetCountBefore); - String args = "\"" + Base58.encode58Check(tokenReceiver) + "\""; - logger.info("args: " + args); - String triggerTxid = PublicMethed - .triggerContract(tokenSender, "sendTRC10(address)", args, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = - PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - Long senderAssetCountAfter = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountAfter); - - Long receiverAssetCountAfterTrigger = PublicMethed - .getAssetIssueValue(tokenReceiver, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + receiverAssetCountAfterTrigger); - Assert.assertTrue(1 == senderAssetCountBefore - senderAssetCountAfter); - Assert.assertTrue(1 == receiverAssetCountAfterTrigger - receiverAssetCountBefore); - - } - - @Test(enabled = true, description = "transfer 1 trc10 to normal address by assembly") - public void transferTokenToNormalAddress() { - long senderAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountBefore); - - long devAssetCountBeforeTrigger = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfterTrigger: " + devAssetCountBeforeTrigger); - - String args = "\"" + Base58.encode58Check(dev001Address) + "\""; - logger.info("args: " + args); - String triggerTxid = PublicMethed - .triggerContract(tokenSender, "sendTRC10(address)", args, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = - PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - long senderAssetCountAfter = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountAfter); - - long devAssetCountAfterTrigger = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfterTrigger: " + devAssetCountAfterTrigger); - Assert.assertTrue(1 == senderAssetCountBefore - senderAssetCountAfter); - Assert.assertTrue(1 == devAssetCountAfterTrigger - devAssetCountBeforeTrigger); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java deleted file mode 100644 index 814c9e38bd2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.addressStrictCheck; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class AddressStrictCheck001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Open experimental check address ") - public void test01CheckAddressNew() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/addressCheckNew.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "00000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - num = "10000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("AAAAA:" + transactionExtention.toString()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java deleted file mode 100644 index e64b30b47f1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.addressStrictCheck; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class AddressStrictCheck002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Close experimental check address") - public void test01AddressOld() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/addressCheckOld.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "00000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info(infoById.toString()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - num = "10000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - logger.info(infoById.toString()); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java deleted file mode 100644 index f1b846be342..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java +++ /dev/null @@ -1,368 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 16 signatures test pure multivalidatesign") - public void test01Correct16signatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertEquals( - "class org.tron.core.vm.program.Program$OutOfTimeException " - + ": CPU timeout for 'ISZERO' operation executing", - transactionExtention.getResult().getMessage().toStringUtf8()); - } else { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures test" - + " pure multivalidatesign") - public void test02Incorrect1stSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "13 signatures with 1st incorrect address test" - + " pure multivalidatesign") - public void test03Incorrect1stAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 13; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01111111111110000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 15th incorrect signatures" - + " test pure multivalidatesign") - public void test04Incorrect15thSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 14) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh123770807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111111111111010000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "15 signatures with 10th-15th incorrect address" - + " test pure multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 15; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 9; i < 14; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111111100000100000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 2nd/16th incorrect signatures" - + " test pure multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 15) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("10111111111111100000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" - + " test pure multivalidatesign") - public void test07IncorrectAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(5, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(12, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111011010101110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash" - + " test pure multivalidatesign") - public void test08IncorrectHash() { - String txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java deleted file mode 100644 index c0bb3e908a4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java +++ /dev/null @@ -1,675 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 16 signatures test multivalidatesign") - public void test01Correct16signatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "13 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 13; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111110000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 15th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 14) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh123770807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("11111111111111010000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "15 signatures with 10th-15th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 15; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 9; i < 14; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111111100000100000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 2nd、16th incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 15) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("10111111111111100000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(5, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(12, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111011010101110000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java deleted file mode 100644 index 4c1d12e6569..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java +++ /dev/null @@ -1,302 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "13 signatures and 12 address test pure multivalidatesign") - public void test01With25SignaturesAnd24Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 12; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "7 signatures and 8 address test pure multivalidatesign") - public void test02With15SignaturesAnd16Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 7; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "150 signatures and 1 address test pure multivalidatesign") - public void test03With150SignaturesAnd1Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 150; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "1 signatures and 160 address test pure multivalidatesign") - public void test04With1SignaturesAnd160Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 160; i++) { - ECKey key = new ECKey(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures and 17 address test pure multivalidatesign") - public void test05With32SignaturesAnd33Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "17 signatures and 16 address test pure multivalidatesign") - public void test06With33SignaturesAnd32Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java deleted file mode 100644 index f1a3eafa181..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java +++ /dev/null @@ -1,534 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "10 signatures and 9 address test multivalidatesign") - public void test01With25SignaturesAnd24Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 9; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures and 15 address test multivalidatesign") - public void test02With15SignaturesAnd16Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "40 signatures and 1 address test multivalidatesign") - public void test03With40SignaturesAnd1Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 40; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "1 signatures and 50 address test multivalidatesign") - public void test04With1SignaturesAnd50Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 50; i++) { - ECKey key = new ECKey(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures and 17 address test multivalidatesign") - public void test05With32SignaturesAnd33Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "17 signatures and 16 address test multivalidatesign") - public void test06With33SignaturesAnd32Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java deleted file mode 100644 index 5277eb725f4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class batchValidateSignContract005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Hash is empty test multivalidatesign") - public void test01HashIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Address is empty test multivalidatesign") - public void test02AddressIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Signatures is empty test multivalidatesign") - public void test03SignaturesIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Signatures and addresses are empty test multivalidatesign") - public void test04SignaturesAndAddressesAreEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "All empty test multivalidatesign") - public void test05AllEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java deleted file mode 100644 index bbc541830c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java +++ /dev/null @@ -1,426 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class batchValidateSignContract006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Hash is empty test multivalidatesign") - public void test01HashIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Address is empty test multivalidatesign") - public void test02AddressIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Signatures is empty test multivalidatesign") - public void test03SignaturesIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Signatures and addresses are empty test multivalidatesign") - public void test04SignaturesAndAddressesAreEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "All empty test multivalidatesign") - public void test05AllEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java deleted file mode 100644 index b252c7170f6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Constructor test multivalidatesign") - public void test01Constructor() { - String txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 2000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "src/test/resources/soliditycode/batchvalidatesign007.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String data = PublicMethed.parametersString(parameters); - String constructorStr = "constructor(bytes32,bytes[],address[])"; - txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Long fee1 = infoById.get().getFee(); - Long netUsed1 = infoById.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testConstructorPure()", "", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - txid = PublicMethed - .triggerContract(contractAddress, "testConstructor()", "", false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById2.get().getResultValue() == 0) { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(infoById2.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById2.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById2.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee2 = infoById2.get().getFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee2:" + fee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee1 + fee2 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed1 + energyUsed2 >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed1 + netUsed2 >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed1 + netUsed2 >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java deleted file mode 100644 index 9f9b8b30512..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java +++ /dev/null @@ -1,146 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Incorrect address hex test pure multivalidatesign") - public void test01IncorrectAddressHex() { - String input = "7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e00000000000000" - + "000000000000000000000000000000000000000000000000600000000000000000000000000000000000000" - + "0000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000" - + "000200000000000000000000000000000000000000000000000000000000000000400000000000000000000" - + "0000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000" - + "0000000000000000000041ad7ca8100cf0ce028b83ac719c8458655a6605317abfd071b91f5cc14d53e87a2" - + "99fe0cdf6a8567074e9be3944affba33b1e15d14b7cb9003ec2c87cb1a56405000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000417ce31e565fb99451f87db65e75f46672e8a8f7b29e6589e60fd11e076550d0a66d0b05" - + "e4b4d7d40bd34140f13dc3632d3ce0f25e4cf75840238b6fe2346c94fa01000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000410d6b1de9e84c1d7a9a5b43d93dbe4a5aae79b18900000000000" - + "00000000000123456"; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, true, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - Assert.assertEquals("", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("REVERT opcode executed", - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "Empty address and signatures hex" - + " test pure multivalidatesign") - public void test02EmptyAddressAndSignaturesHex() { - String input = "da586d881362c0c38eb31b556ce0f7c2837a3ebb60080e8e665a6b92c7541837b95064ba000000" - + "000000000000000000000000000000000000000000000000000000006000000000000000000000000000000" - + "000000000000000000000000000000001200000000000000000000000000000000000000000000000000000" - + "000000000001000000000000000000000000000000000000000000000000000000000000002000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000001000000000000000000000000000000000000000" - + "0000000000000000000000000"; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, true, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - Assert.assertEquals("", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("REVERT opcode executed", - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java deleted file mode 100644 index fb9a8325914..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java +++ /dev/null @@ -1,225 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Incorrect address hex test multivalidatesign") - public void test02IncorrectAddressHex() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e00000000000000" - + "000000000000000000000000000000000000000000000000600000000000000000000000000000000000000" - + "0000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000" - + "000200000000000000000000000000000000000000000000000000000000000000400000000000000000000" - + "0000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000" - + "0000000000000000000041ad7ca8100cf0ce028b83ac719c8458655a6605317abfd071b91f5cc14d53e87a2" - + "99fe0cdf6a8567074e9be3944affba33b1e15d14b7cb9003ec2c87cb1a56405000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000417ce31e565fb99451f87db65e75f46672e8a8f7b29e6589e60fd11e076550d0a66d0b05" - + "e4b4d7d40bd34140f13dc3632d3ce0f25e4cf75840238b6fe2346c94fa01000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000410d6b1de9e84c1d7a9a5b43d93dbe4a5aae79b18900000000000" - + "00000000000123456"; - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, true, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertTrue( - infoById.get().getResMessage().toStringUtf8().contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Empty address and signatures hex test multivalidatesign") - public void test03EmptyAddressAndSignaturesHex() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "da586d881362c0c38eb31b556ce0f7c2837a3ebb60080e8e665a6b92c7541837b95064ba000000" - + "000000000000000000000000000000000000000000000000000000006000000000000000000000000000000" - + "000000000000000000000000000000001200000000000000000000000000000000000000000000000000000" - + "000000000001000000000000000000000000000000000000000000000000000000000000002000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000001000000000000000000000000000000000000000" - + "0000000000000000000000000"; - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, true, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertTrue( - infoById.get().getResMessage().toStringUtf8().contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java deleted file mode 100644 index 663be1160c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract010 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 50 signatures test multivalidatesign") - public void test01Correct50Signatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 50; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "2 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 2; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "3 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 3; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01100000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "9 signatures with 7th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 9; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(6, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111101100000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "5 signatures with 2th-4th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 5; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 1; i < 4; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("10001000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "150 signatures with 2nd/32nd incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 150; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 31) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "88 signatures with 9th/11th/28th/32nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 88; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(27, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(31, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "105 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 105; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java deleted file mode 100644 index 1697784e7e3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java +++ /dev/null @@ -1,695 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract011 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 17 signatures test multivalidatesign") - public void test01Correct33Signatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 17; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "8 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 8; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "6 signatures with 3th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 6; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(2, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11011100000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "11 signatures with 7th-9th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 11; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 6; i < 9; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111100011000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "40 signatures with 2nd、32nd incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 40; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 31) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "44 signatures with 9th/11th/28th/32nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 44; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(27, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(31, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java deleted file mode 100644 index c35abd39f78..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java +++ /dev/null @@ -1,172 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract012 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign005.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger precompile multivalisign function with correct data") - public void test01TriggerPrecompileMultivalisignWithCorrectData() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters("batchvalidatesign(bytes32,bytes[],address[])", argsStr); - String method = "testArray2(bytes)"; - txid = PublicMethed.triggerContractBoth(contractAddress, method, - AbiUtil.parseParameters(method, Arrays.asList(input)), true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - PublicMethed.getTransactionById(txid, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info( - "infoById:" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .equals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0101010101010101010101010101010100000000000000000000000000000000")); - } - - @Test(enabled = true, description = "Trigger precompile multivalidatesign function with incor" - + "rect data") - public void test02TriggerPrecompileMultivalisignWithIncorrectData() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters("batchvalidatesign(bytes32,bytes[],address[])", argsStr); - String method = "testArray2(bytes)"; - txid = PublicMethed.triggerContractBoth(contractAddress, method, - AbiUtil.parseParameters(method, Arrays.asList(input)), true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - PublicMethed.getTransactionById(txid, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info( - "infoById:" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .equals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0001010101010101010101010101010100000000000000000000000000000000")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java deleted file mode 100644 index aeb7f5d6e85..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java +++ /dev/null @@ -1,301 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress1, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Clear a contract created by other account") - public void testClearAbi001() { - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractAddress, contractExcAddress1, contractExcKey1, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("is not the owner of the contract")); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi002() { - - String contractName = "testConstantContract"; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String txid1 = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - - @Test(enabled = true, description = "Clear a contract without ABI") - public void testClearAbi003() { - - String contractName = "testConstantContract"; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - @Test(enabled = true, description = "Clear a account address") - public void testClearAbi004() { - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - } - - - @Test(enabled = true, description = "Clear a uninitialized account") - public void testClearAbi005() { - - ECKey ecKeyN = new ECKey(Utils.getRandom()); - byte[] contractExcAddressN = ecKeyN.getAddress(); - String contractExcKeyN = ByteArray.toHexString(ecKeyN.getPrivKeyBytes()); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddressN, contractExcAddress, contractExcKey, - blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - } - - @Test(enabled = true, description = "Clear a not meet the rules address") - public void testClearAbi006() { - byte[] fakeAddress = "412B5D".getBytes(); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(fakeAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - byte[] fakeAddress1 = "412B5D3405B2D26767C9C09886D53DEAFF6EB718AC111".getBytes(); - - TransactionExtention transactionExtention1 = PublicMethed - .clearContractAbiForExtention(fakeAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention1.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention1.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed.freedResource(contractExcAddress1, contractExcKey1, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java deleted file mode 100644 index b949713f0ab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java deleted file mode 100644 index 3daf89fc406..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java +++ /dev/null @@ -1,148 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract without ABI") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java deleted file mode 100644 index efa7f20f6d8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java +++ /dev/null @@ -1,115 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a account address") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java deleted file mode 100644 index 0af7a1bf2f1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java +++ /dev/null @@ -1,197 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract created by create2 (without ABI)") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(returnAddressBytes, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("is not the owner of the contract")); - - smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - - /** - * testClearAbitestClearAbi constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java deleted file mode 100644 index 25e85fe9e73..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a uninitialized account") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java deleted file mode 100644 index 02bf0babc42..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a not meet the rules address") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] fakeAddress = "412B5D".getBytes(); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(fakeAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - byte[] fakeAddress1 = "412B5D3405B2D26767C9C09886D53DEAFF6EB718AC111".getBytes(); - - TransactionExtention transactionExtention1 = PublicMethed - .clearContractAbiForExtention(fakeAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention1.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention1.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java deleted file mode 100644 index c12802bab0a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java +++ /dev/null @@ -1,162 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself," - + "clear a contract by itself again") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - String txid1 = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java deleted file mode 100644 index fc6e57905ae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java +++ /dev/null @@ -1,356 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class NoAbi009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress1, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "clearabi contract with event") - public void testNoAbi001() { - String filePath = "src/test/resources/soliditycode/NoAbi001.sol"; - String contractName = "testNoABiContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - // getcontract - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - System.out.println("smartContract:" + smartContract.toString()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - // getcontractinfo - SmartContractDataWrapper contractInfo = PublicMethed - .getContractInfo(contractAddress, blockingStubFull); - System.out.println("contractInfo.toString():" + contractInfo.toString()); - Assert.assertTrue(contractInfo.getSmartContract().getAbi().toString().isEmpty()); - Assert.assertTrue(contractInfo.getSmartContract().getName().equalsIgnoreCase(contractName)); - Assert.assertTrue(contractInfo.getRuntimecode().size() > 0); - Assert.assertFalse(contractInfo.getSmartContract().getBytecode().toString().isEmpty()); - - // triggerconstantcontract fullnode - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testTrigger()", "#", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(3, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // triggercontract - txid = PublicMethed - .triggerContract(contractAddress, "testTrigger()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Long returnNumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(3 == returnNumber); - List retList = PublicMethed - .getStrings(infoById.get().getLogList().get(0).getData().toByteArray()); - logger.info("retList:" + retList.toString()); - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(1)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - Assert.assertEquals(WalletClient.encode58Check(contractExcAddress),addressFinal); - Long actualNum = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Assert.assertEquals(returnNumber,actualNum); - - // triggerconstantcontract solidity - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(contractAddress, "testTrigger()", "#", - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(4, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "create2 contract with event") - public void testNoAbi002() { - String filePath = "./src/test/resources/soliditycode/NoAbi002.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractExcKey1, - contractExcAddress1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - byte[] factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - contractName = "testNoABiContract"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testNoABiContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - String param = "\"" + testNoABiContractCode + "\"," + salt; - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, Long.valueOf(0), - 1000000000L, "0", 0, contractExcAddress1, contractExcKey1, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - byte[] testNoABiContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - // getcontract - smartContract = PublicMethed.getContract(testNoABiContractAddress, blockingStubFull); - System.out.println("smartContract:" + smartContract.toString()); - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - // Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - // getcontractinfo - SmartContractDataWrapper contractInfo = PublicMethed - .getContractInfo(testNoABiContractAddress, blockingStubFull); - System.out.println("contractInfo.toString():" + contractInfo.toString()); - Assert.assertTrue(contractInfo.getSmartContract().getAbi().toString().isEmpty()); - // Assert.assertTrue(contractInfo.getSmartContract().getName().equalsIgnoreCase(contractName)); - Assert.assertTrue(contractInfo.getRuntimecode().size() > 0); - Assert.assertFalse(contractInfo.getSmartContract().getBytecode().toString().isEmpty()); - - // triggerconstantcontract fullnode - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(testNoABiContractAddress, "plusOne()", "#", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // triggercontract - String txid = PublicMethed - .triggerContract(testNoABiContractAddress, "plusOne()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Long returnNumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnNumber); - retList = PublicMethed - .getStrings(infoById.get().getLogList().get(0).getData().toByteArray()); - logger.info("retList:" + retList.toString()); - tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(1)), 12, tmpAddress, 0, 20); - addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - Assert.assertEquals(WalletClient.encode58Check(contractExcAddress),addressFinal); - Long actualNum = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Assert.assertEquals(returnNumber,actualNum); - - // triggerconstantcontract solidity - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(testNoABiContractAddress, "plusOne()", "#", - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(2, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed.freedResource(contractExcAddress1, contractExcKey1, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java deleted file mode 100644 index ce88b68644b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java +++ /dev/null @@ -1,558 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] factoryContractAddress = null; - private byte[] factoryContractAddress2 = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 command with test bytecode using factory. ") - public void test02TriggerCreate2ToDeployTestContract() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // different contract address with different bytecode, same salt and address - Assert.assertNotEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(testContractAddress)); - } - - @Test(enabled = true, description = "Trigger create2 command with factory bytecode") - public void test02TriggerCreate2ToDeployFactory2Contract() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - factoryContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed - .getContract(factoryContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 command with test bytecode using factory2") - public void test03TriggerCreate2ToDeployTestContract2() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress2, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - // Istanbul change create2 algorithm - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = true, description = "Trigger create2 command without meta data hash in bytecode") - public void test04TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String msgSender = Base58.encode58Check(ByteArray.fromHexString(retList.get(2))); - Assert.assertNotEquals(msgSender, Base58.encode58Check(user001Address)); - } - - @Test(enabled = true, description = "Trigger create2 command with 0 extended bytecode") - public void test05TriggerCreate2ToDeployTestContract() { - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe0000000000000000000000000000000000000000000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - } - - @Test(enabled = true, description = "Trigger Test contact") - public void test04TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java deleted file mode 100644 index a708e96c3aa..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java +++ /dev/null @@ -1,324 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - //PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command without meta data hash in bytecode") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String msgSender = Base58.encode58Check(ByteArray.fromHexString(retList.get(2))); - Assert.assertNotEquals(msgSender, Base58.encode58Check(user001Address)); - } - - - @Test(enabled = false, description = "Trigger Test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java deleted file mode 100644 index bc536e7caf4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java +++ /dev/null @@ -1,489 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 command with invalid bytecode") - public void test02TriggerCreate2WithInvalidBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f5fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fea165627a7a72305820f3e3c0646a8c8d521fe819f10a592327469f611f0d9e8206697f7f" - + "3436ff3c7d0029"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with empty bytecode") - public void test03TriggerCreate2WithEmptyBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = ""; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with \"6080\" bytecode") - public void test04TriggerCreate2WithShortBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "6080"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with \"00000000000\" bytecode") - public void test05TriggerCreate2WithZeroBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with NULL bytecode") - public void test06TriggerCreate2WithNullBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = null; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - boolean ret = false; - - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (org.bouncycastle.util.encoders.DecoderException e) { - logger.info("Expected org.bouncycastle.util.encoders.DecoderException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java deleted file mode 100644 index 17e87b7d289..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java +++ /dev/null @@ -1,470 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] factoryContractAddress2 = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore));*/ - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 command with factory bytecode") - public void test02TriggerCreate2ToDeployFactory2Contract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 150000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - factoryContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed - .getContract(factoryContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode using factory") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // different contract address with different bytecode, same salt and address - Assert.assertNotEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(testContractAddress)); - } - - @Test(enabled = false, description = "Trigger create2 command with test bytecode using factory2") - public void test04TriggerCreate2ToDeployTestContract2() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress2, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("Not enough energy for 'SWAP1' operation executing")); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java deleted file mode 100644 index 9ec661328e6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command with 0 extended bytecode") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe0000000000000000000000000000000000000000000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java deleted file mode 100644 index fdd0504c242..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java +++ /dev/null @@ -1,1014 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 with salt empty") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String param = "\"" + testContractCode + "\"," + null; - boolean ret = false; - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Trigger create2 with salt 0") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 0L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt -1") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = -1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt 100") - public void test05TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 100L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Trigger create2 with salt f * 64") - public void test06TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String saltHexString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(saltHexString, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt efffe") - public void test07TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "EFFFE"; - final String expectedSalt = "0EFFFE0000000000000000000000000000000000000000000000000000000000"; - - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt affffa") - public void test08TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "AFFFFA"; - final String expectedSalt = "AFFFFA0000000000000000000000000000000000000000000000000000000000"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Trigger test contract") - public void test09TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java deleted file mode 100644 index 135a76a7560..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt -1") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = -1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java deleted file mode 100644 index b278ff2ccac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt 100") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 100L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java deleted file mode 100644 index fc3132c2d72..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java +++ /dev/null @@ -1,365 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 function to deploy test contract") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Assert.assertEquals(Base58.encode58Check(testContractAddress), PublicMethed.create2(parameter)); - - } - - - @Test(enabled = false, description = "Trigger Test contact") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java deleted file mode 100644 index cd32b9c983d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java +++ /dev/null @@ -1,210 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test010 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "TransferToken with correct value, deploy transfer contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 with salt empty") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String param = "\"" + testContractCode + "\"," + null; - boolean ret = false; - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java deleted file mode 100644 index 93a149c6298..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java +++ /dev/null @@ -1,369 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "FactoryBytes"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 with salt f * 64") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String saltHexString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(saltHexString, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java deleted file mode 100644 index f4a906c3af3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java +++ /dev/null @@ -1,396 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode and salt 1") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode and salt 2") - public void test03TriggerCreate2ToDeployTestContract2() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 2L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // contract address are different with different salt - Assert.assertNotEquals(Base58.encode58Check(testContractAddress), - Base58.encode58Check(testContractAddress2)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java deleted file mode 100644 index d1b1ebba816..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java +++ /dev/null @@ -1,436 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger factory contract to deploy test contract") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger factory contract to deploy test contract again " - + "with same code, salt and address") - public void test03TriggerCreate2ToDeployTestContractAgain() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("Not enough energy for 'SWAP1' operation executing")); - } - - @Test(enabled = false, description = "Trigger test1 contract") - public void test04TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java deleted file mode 100644 index 127eac0aad9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java +++ /dev/null @@ -1,641 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "Trigger factory contract with Test " - + "bytecode and salt using user account") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger factory contract to deploy test contract again " - + "with same code, salt and address") - public void test02TriggerCreate2ToDeployTestContractAgain() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Same code, salt and address," - + " create contract using develop account") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // contract address are different - Assert.assertNotEquals(Base58.encode58Check(testContractAddress), - Base58.encode58Check(testContractAddress2)); - } - - @Test(enabled = true, description = "Trigger test1 contract") - public void test04TriggerTest1Contract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Trigger test2 contract") - public void test05TriggerTest2Contract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress2, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java deleted file mode 100644 index c61b9befe1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java +++ /dev/null @@ -1,499 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test015 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] callerContractAddress = null; - private byte[] callContractAddress = null; - private byte[] delegateCallContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy caller contract") - public void test01DeployCallerContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2CallContract.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - callerContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(callerContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test02DeployFactoryContract() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger callCreate2 function in caller contract " - + "with factory contract address") - public void test03TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "callCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), - 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - callContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(callContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of - // test contract (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger delegateCallCreate2 function in caller contract " - + "with factory contract address") - public void test04TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "delegateCallCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - delegateCallContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed - .getContract(delegateCallContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // delegatecall type make the caller contract to be the owner of test contract (contract info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of test contract - // (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger test contract") - public void test09TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(callContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java deleted file mode 100644 index 055f55a982f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java +++ /dev/null @@ -1,422 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test016 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] callerContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy caller contract") - public void test01DeployCallerContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2CallContract.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - callerContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(callerContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test02DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger delegateCallCreate2 function in caller contract " - + "with factory contract address") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "delegateCallCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // delegatecall type make the caller contract to be the owner of test contract (contract info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of test contract - // (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test04TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java deleted file mode 100644 index 6346c900d21..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java +++ /dev/null @@ -1,405 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test017 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "FactoryBytes"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt efffe") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "EFFFE"; - final String expectedSalt = "0EFFFE0000000000000000000000000000000000000000000000000000000000"; - - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger create2 with salt affffa") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "AFFFFA"; - final String expectedSalt = "AFFFFA0000000000000000000000000000000000000000000000000000000000"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java deleted file mode 100644 index 858d167c80d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test018 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(witnessKey001); - } - - @Test(enabled = false, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(witnessAddress001, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 function to deploy test contract " - + "using Witness account") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 9000_000_000_000L, 0, 1, - ByteString.copyFrom(witnessAddress001), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = new Random().nextLong(); - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, witnessAddress001, witnessKey001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger Test contact") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(witnessAddress001, witnessKey001, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(witnessAddress001), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, witnessAddress001, witnessKey001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - witnessAddress001, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - witnessAddress001, blockingStubFull); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java deleted file mode 100644 index d903550be89..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java +++ /dev/null @@ -1,297 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test019 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "seted Value of Contract that created by create2," - + " should not be stored after contact suicided ande create2 again") - public void testTriggerContract() { - String sendcoin = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - String filePath = "src/test/resources/soliditycode/create2contractn2.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "set()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(5 == returnnumber); - - String param1 = "\"" + Base58.encode58Check(returnAddressBytes) + "\""; - - txid = PublicMethed - .triggerContract(returnAddressBytes, - "testSuicideNonexistentTarget(address)", param1, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals("suicide", ByteArray - .toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray())); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : No contract or not a valid smart contract")); - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] returnAddressBytes1 = infoById3.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress1 = Base58.encode58Check(returnAddressBytes1); - Assert.assertEquals(returnAddress1, returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes1, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java deleted file mode 100644 index 5329174e028..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java +++ /dev/null @@ -1,896 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test020 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : trcToken") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 500000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1000001; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,trcToken)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : uint8") - public void testTriggerContract1() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1000031; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy1(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : address") - public void testTriggerContract2() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy2(bytes,address)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : string") - public void testTriggerContract3() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract4() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract1"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(2 == returnnumber); - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract5() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract2"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(3 == returnnumber); - num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(testNetAccountAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract6() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract3"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(4 == returnnumber); - String fakeAddress = "FFFFFFF"; - - num = "\"" + code1 + "\"" + ",\"" + fakeAddress + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java deleted file mode 100644 index fafbd5244fe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java +++ /dev/null @@ -1,372 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test021 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Asset008_" + Long.toString(now); - private static final long totalSupply = now; - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] bytes; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ByteString assetAccountId = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] resourceOnwerAddress = ecKey2.getAddress(); - String resourceOnwerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] contractExcAddress = ecKey3.getAddress(); - private String contractExcKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(resourceOnwerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = true, description = "resource delegate with create2 contract, and suicide ") - public void test1TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(resourceOnwerAddress, 1000000000L + 1024000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create 3 the same name token. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(resourceOnwerAddress, - name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, resourceOnwerKey, blockingStubFull)); - String filePath = "src/test/resources/soliditycode/create2contractn.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - - Long beforeExcAccountBalance = PublicMethed - .queryAccount(resourceOnwerAddress, blockingStubFull).getBalance(); - // create2 TestContract - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - - bytes = returnAddressBytes; - - - // freezeBalanceForReceiver to create2 contract Address, transaction Failed - - Assert.assertFalse(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 5000000L, 0, 0, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 5000000L, 0, 1, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Long afterExcAccountBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - Assert.assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getNetLimit() == 0); - Assert - .assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getEnergyLimit() == 0); - logger.info("afterExcAccountBalance: " + afterExcAccountBalance); - logger.info("beforeExcAccountBalance:" + beforeExcAccountBalance); - - Assert.assertTrue(afterExcAccountBalance - beforeExcAccountBalance == 0); - - - // create2 Address Suicide - String param2 = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - String txidn = PublicMethed - .triggerContract(bytes, - "testSuicideNonexistentTarget(address)", param2, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - // active create2 Address to normal Address - Assert.assertTrue(PublicMethed - .sendcoin(bytes, 1000000L, contractExcAddress, contractExcKey, blockingStubFull)); - //Trigger contract to transfer trx and token. - Account getAssetIdFromAccount = PublicMethed - .queryAccount(resourceOnwerAddress, blockingStubFull); - assetAccountId = getAssetIdFromAccount.getAssetIssuedID(); - Long contractBeforeBalance = PublicMethed.queryAccount(bytes, blockingStubFull).getBalance(); - - Assert.assertTrue( - PublicMethed.transferAsset(bytes, assetAccountId.toByteArray(), 100, resourceOnwerAddress, - resourceOnwerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account account1 = PublicMethed.queryAccount(bytes, blockingStubFull); - int typeValue1 = account1.getTypeValue(); - Assert.assertEquals(0, typeValue1); - - // freezeBalanceForReceiver to "create2" contract Address, transaction SUCCESS - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 1000000L, 0, 0, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 1000000L, 0, 1, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - beforeExcAccountBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(PublicMethed.unFreezeBalance(resourceOnwerAddress, resourceOnwerKey, - 0, bytes, blockingStubFull)); - Assert.assertTrue(PublicMethed.unFreezeBalance(resourceOnwerAddress, resourceOnwerKey, - 1, bytes, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterUnfreezeBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - Assert.assertTrue(afterUnfreezeBalance == beforeExcAccountBalance + 1000000L * 2); - - - // create2 TestContract to turn AccountType To create2 Contract Address - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - // triggercontract Create2 address, function normal - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - Account account = PublicMethed.queryAccount(returnAddressBytes, blockingStubFull); - int typeValue = account.getTypeValue(); - Assert.assertEquals(2, typeValue); - Assert.assertEquals(account.getBalance(), 1000000); - } - - @Test(enabled = true, description = "Create2 contract can transfer trx and token.") - public void test2TriggerContract() { - Account accountbefore = PublicMethed.queryAccount(bytes, blockingStubFull); - int typeValue = accountbefore.getTypeValue(); - Assert.assertEquals(2, typeValue); - long accountbeforeBalance = accountbefore.getBalance(); - Assert.assertEquals(accountbeforeBalance, 1000000); - Account contractExcAddressbefore = PublicMethed - .queryAccount(contractExcAddress, blockingStubFull); - long contractExcAddressbeforeBalance = contractExcAddressbefore.getBalance(); - - String num = "1"; - - String txid = PublicMethed - .triggerContract(bytes, - "testTransfer(uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(transactionInfoById.get().getResultValue() == 0); - Long fee1 = transactionInfoById.get().getFee(); - - Account accountafter = PublicMethed.queryAccount(bytes, blockingStubFull); - long accountafterBalance = accountafter.getBalance(); - Assert.assertTrue(accountbeforeBalance - 1 == accountafterBalance); - - Account contractExcAddressafter = PublicMethed - .queryAccount(contractExcAddress, blockingStubFull); - long contractExcAddressafterBalance = contractExcAddressafter.getBalance(); - Assert.assertTrue(contractExcAddressbeforeBalance + 1 - fee1 == contractExcAddressafterBalance); - - num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(bytes, assetAccountId, blockingStubFull); - Long contractExcAddressAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - String txid1 = PublicMethed - .triggerContract(bytes, - "testTransferToken(uint256,trcToken)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(transactionInfoById1.get().getResultValue() == 0); - Long returnAddressBytesAccountCountAfter = PublicMethed - .getAssetIssueValue(bytes, assetAccountId, blockingStubFull); - - Long contractExcAddressAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Assert.assertTrue( - returnAddressBytesAccountCountBefore - 1 == returnAddressBytesAccountCountAfter); - Assert.assertTrue( - contractExcAddressAccountCountBefore + 1 == contractExcAddressAccountCountAfter); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java deleted file mode 100644 index b390698eb60..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test023 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test023.sol"; - String contractName = "factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "contract A new B contract,A suicide,contract B still exist") - public void test02TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "testCreate()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("B Address : " + addressFinal); - - //B Address is created by A, Trigger contract B - triggerTxid = PublicMethed.triggerContract(ByteArray.fromHexString(exceptedResult), - "test()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(ByteArray.toLong(infoById.get().getContractResult(0).toByteArray()), 1); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "kill()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("suicide", note); - - triggerTxid = PublicMethed.triggerContract(ByteArray.fromHexString(exceptedResult), - "test()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java deleted file mode 100644 index 8c42a4362ec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test024 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test024.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "create2 not allowed create2 twice in function") - public void test02TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/Create2Test024.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 4L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("create2 Address : " + addressFinal); - - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(infoById.get().getResultValue(), 0); - - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy2(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitAfter = accountResource.getEnergyLimit(); - devEnergyUsageAfter = accountResource.getEnergyUsed(); - devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - userEnergyLimitAfter = accountResource.getEnergyLimit(); - userEnergyUsageAfter = accountResource.getEnergyUsed(); - userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResult().toString(), "FAILED"); - Assert.assertThat(ByteArray.toStr(infoById.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java deleted file mode 100644 index be459a86a81..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java +++ /dev/null @@ -1,263 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test025 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test025.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - code += "05"; - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "create2 bytecode with parm") - public void test02TriggerTestContract() { - //Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - // PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - // blockingStubFull), 0, 1, - // ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test025.sol"; - String contractName = "TestContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - testContractCode += "0000000000000000000000000000000000000000000000000000000000000005"; - Long salt = 4L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = null; - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "create2(bytes,uint256)", param, false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String txid = PublicMethed.triggerContract(testContractAddress, - "getNum()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - Optional infoById2 = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - TransactionInfo transactionInfo2 = infoById2.get(); - final int Num = ByteArray.toInt(transactionInfo2.getContractResult(0).toByteArray()); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - userEnergyLimitAfter = accountResource.getEnergyLimit(); - userEnergyUsageAfter = accountResource.getEnergyUsed(); - userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - logger.info("NUM :" + Num); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(5, Num); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java deleted file mode 100644 index ecc505fa210..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java +++ /dev/null @@ -1,689 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - private String testContractAddress2 = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Get the extcodehash of a normal address") - public void test02GetNormalAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(dev001Address) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " - + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - } - - @Test(enabled = true, description = "Get a contract extcodehash") - public void test03GetContactCodeHash() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Get a not exist account extcodehash") - public void test04GetNotExistAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Active the account and get extcodehash again") - public void test05ActiveAccountGetCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(testAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - } - - @Test(enabled = true, description = "Get a not deployed create2 extcodehash") - public void test06GetCreate2CodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - Long salt = 100L; - String[] parameter = {Base58.encode58Check(user001Address), code, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - testContractAddress2 = PublicMethed.create2(parameter); - - Long callValue = Long.valueOf(0); - - String param = "\"" - + Base58.encode58Check(WalletClient.decodeFromBase58Check(testContractAddress2)) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - /*PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull);*/ - } - - @Test(enabled = true, description = "Get the EXTCODEHASH of an account created " - + "in the current transaction") - public void test07DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashConstruct.sol"; - String contractName = "CounterConstruct"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getTopics(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java deleted file mode 100644 index 9fbe6334872..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java +++ /dev/null @@ -1,246 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest002 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a contract extcodehash") - public void test02GetContactCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java deleted file mode 100644 index e6f29b2eaf0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java +++ /dev/null @@ -1,336 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest003 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a not exist account extcodehash") - public void test02GetNotExistAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = AllTest, description = "Active the account and get extcodehash again") - public void test03ActiveAccountGetCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(testAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java deleted file mode 100644 index 8e64990fe57..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java +++ /dev/null @@ -1,256 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import static org.tron.common.crypto.Hash.sha3; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest004 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private String testContractAddress = null; - - private String expectedCodeHash = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - Long salt = 100L; - String[] parameter = {Base58.encode58Check(user001Address), code, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - testContractAddress = PublicMethed.create2(parameter); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a not deployed create2 extcodehash") - public void test02GetCreate2CodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = - "\"" + Base58.encode58Check(WalletClient.decodeFromBase58Check(testContractAddress)) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java deleted file mode 100644 index 060b9b8e999..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java +++ /dev/null @@ -1,713 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String contractCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - - String fakeAddress = ""; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - fakeAddress = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - - logger.info("realAddress: " + fakeAddress); - fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Get codehash of a real contract by uint") - public void test02GetContractCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testAddress = ByteArray.toHexString(extCodeHashContractAddress); - logger.info("realAddress: " + testAddress); - byte[] fullHexAddr = new DataWord(testAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - contractCodeHash = retList.get(0); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a fake address by uint") - public void test03GetInvalidAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = "41660757B2543F4849D3F42B90F58DE1C14C7E0038"; - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a normal account by uint") - public void test04GetNormalAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = ByteArray.toHexString(user001Address); - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a empty address by uint") - public void test05GetEmptyAddressCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = ""; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a fffffff*64 address by uint") - public void test06GetFakeAddressCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a real contract plus 2**160 by uint") - public void test07GetContractAddress96CodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - BigInteger bigIntAddr = new DataWord(extCodeHashContractAddress).sValue(); - String bigIntAddrChange = BigInteger.valueOf(2).pow(160).add(bigIntAddr).toString(16); - byte[] fullHexAddr = new DataWord(bigIntAddrChange).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - // expect the code hash same - Assert.assertEquals(contractCodeHash, retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java deleted file mode 100644 index a0723bbe817..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java +++ /dev/null @@ -1,185 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest006 { - - private final boolean AllTest = false; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Get the EXTCODEHASH of an account created " - + "in the current transaction") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashConstruct.sol"; - String contractName = "CounterConstruct"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getTopics(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java deleted file mode 100644 index ddf712a08e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java +++ /dev/null @@ -1,617 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] testAddressOld = null; - private byte[] testAddressNew = null; - private byte[] testAddress2 = null; - private byte[] extCodeHashContractAddress = null; - - private String expectedCodeHash = null; - private String expectedCodeHashOld = null; - - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy testNoPayable contract using old solidity") - public void test01DeployTestContractOld() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testExtHashContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b5060ef806100396000396000f30060806040526004361060485763ffffffff7c010000000000000000" - + "0000000000000000000000000000000000000000600035041663c518aa0f8114604d578063e5aa3d58146089" - + "575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd5b5060" - + "7760b3565b60408051918252519081900360200190f35b348015609457600080fd5b50d3801560a057600080" - + "fd5b50d2801560ac57600080fd5b50607760bd565b6001600081905590565b600054815600a165627a7a7230" - + "5820766b4e2fca9081689cd89419411d2cbc5588a17a5c9fa900fd9cfe4b0d9652be0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\"," - + "\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true," - + "\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}]," - + "\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddressOld = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddressOld, - blockingStubFull); - } - - @Test(enabled = true, description = "Deploy testNoPayable contract using new solidity") - public void test02DeployTestContractNew() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testConstantContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5760" - + "0080fd5b5060c5806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b576000" - + "80fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000000000000" - + "000000000000000000006000350463c518aa0f8114606b578063e5aa3d58146083575b600080fd5b607160" - + "89565b60408051918252519081900360200190f35b60716093565b6001600081905590565b6000548156fe" - + "a165627a7a723058205c5aadfbd06ea264db7b73e7b7f3c36ac64a9d520ba46b4bc7f1dc56252f17ac0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"" - + "type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddressNew = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddressNew, - blockingStubFull); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test03DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get contract code hash with old solidity") - public void test04GetTestOldCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddressOld) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - expectedCodeHashOld = retList.get(0); - Assert.assertEquals( - "B4AB5B9FF1A4FF7793E60EBFF0C769443AF66D0A6F9455AF145432CE8BA78175", expectedCodeHashOld); - Assert.assertFalse(retList.isEmpty()); - } - - @Test(enabled = true, description = "Get contract code hash with new solidity") - public void test05GetTestNewCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddressNew) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertNotEquals(retList.get(0), expectedCodeHashOld); - expectedCodeHash = retList.get(0); - Assert.assertEquals( - "34DB53BD1F7214367E8D6B2A7A6FBBF0E3B7DDB4939ECADE4CDEF6749C27A2DA", expectedCodeHash); - } - - @Test(enabled = true, description = "Deploy contract using new solidity again") - public void test06DeployTest2Contract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testConstantContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5760" - + "0080fd5b5060c5806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b576000" - + "80fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000000000000" - + "000000000000000000006000350463c518aa0f8114606b578063e5aa3d58146083575b600080fd5b607160" - + "89565b60408051918252519081900360200190f35b60716093565b6001600081905590565b6000548156fe" - + "a165627a7a723058205c5aadfbd06ea264db7b73e7b7f3c36ac64a9d520ba46b4bc7f1dc56252f17ac0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"" - + "type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddress2 = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddress2, - blockingStubFull); - } - - @Test(enabled = true, description = "Get contract code hash with test2") - public void test07GetTest2CodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress2) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals(expectedCodeHash, retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java deleted file mode 100644 index 87ac6cddfd3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java +++ /dev/null @@ -1,512 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get code hash of create2 empty contract") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + PublicMethed.create2(parameter) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test03DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 function to deploy test contract") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Get code hash of test contract") - public void test05GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java deleted file mode 100644 index 71b3b7b9274..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java +++ /dev/null @@ -1,512 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get code hash of create2 empty contract") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + PublicMethed.create2(parameter) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test03DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 function to deploy test contract") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Get code hash of test contract") - public void test05GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java deleted file mode 100644 index a9271034372..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java +++ /dev/null @@ -1,370 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest010 { - - final boolean AllTest = false; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/ExtCodeHashTest010.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that selfdestructed in the " - + "current transaction. but later been revert") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashRevert()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that create in the current " - + "transaction. but later been revert") - public void test03GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashCreate()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that selfdestructed in the" - + " current transaction.") - public void test04GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashSuicide(address)", param, false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java deleted file mode 100644 index 20b5267d13f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java +++ /dev/null @@ -1,369 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr()", "#", false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract1() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter1"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr()", "#", false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals(retList.get(1), - retList.get(0)); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract2() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter2"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", num, false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - Assert.assertEquals(retList.get(1), - retList.get(0)); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract3() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter2"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", num, false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - Assert.assertEquals(retList.get(1), - retList.get(0)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java deleted file mode 100644 index 736fa1b5202..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java +++ /dev/null @@ -1,340 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - } - - - @Test(enabled = true, description = "Correct contract address test") - public void test01CorrectContractAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Account address test") - public void test02AccountAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Nonexistent account address test") - public void test03NonexistentAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Constructor return test") - public void test04ConstructorReturn() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, "testConstructor()", "", false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testConstructorView()", "", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java deleted file mode 100644 index 327092c74e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java +++ /dev/null @@ -1,190 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] selfdestructContractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - byte[] selfdestructContractExcAddress = ecKey1.getAddress(); - String selfdestructContractKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(selfdestructContractKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Selfdestruct contract test isContract Command") - public void test01SelfdestructContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - Assert.assertTrue(PublicMethed - .sendcoin(selfdestructContractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - - selfdestructContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, selfdestructContractKey, - selfdestructContractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed.triggerContract(selfdestructContractAddress, - "testIsContractCommand(address)", num, false, - 0, maxFeeLimit, selfdestructContractExcAddress, selfdestructContractKey, blockingStubFull); - Optional infoById1 = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - logger.info(infoById1.toString()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(selfdestructContractAddress, - "testIsContractView(address)", num, false, - 0, 0, "0", 0, selfdestructContractExcAddress, selfdestructContractKey, - blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "selfdestructContract(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - logger.info(infoById1.toString()); - - txid1 = PublicMethed.triggerContract(selfdestructContractAddress, - "testIsContractCommand(address)", num, false, - 0, maxFeeLimit, selfdestructContractExcAddress, selfdestructContractKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertEquals(0, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - logger.info(infoById1.toString()); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(selfdestructContractAddress, - "testIsContractView(address)", num, false, - 0, 0, "0", 0, selfdestructContractExcAddress, selfdestructContractKey, - blockingStubFull); - logger.info("transactionExtention:" + transactionExtention.toString()); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "No constructor test isContract Command") - public void test02NoConstructorContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract002.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(info.get().toString()); - Assert.assertEquals(0, info.get().getResultValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java deleted file mode 100644 index ee33144338f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java +++ /dev/null @@ -1,252 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - byte[] selfdestructContractExcAddress = ecKey1.getAddress(); - String selfdestructContractKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(selfdestructContractKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Incorrect address hex test isContract Command") - public void test01IncorrectHashContract() { - PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "ac5a3e290000000000000000000000123456789123456789"; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testIsContractCommand(address)", input, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8() - .contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testIsContractView(address)", input, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - @Test(enabled = true, description = "Empty addresses hash test isContract Command") - public void test02EmptyAddressHashContract() { - PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String input = "ac5a3e29"; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testIsContractCommand(address)", input, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8() - .contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testIsContractView(address)", input, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java deleted file mode 100644 index 355c8cd30af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java +++ /dev/null @@ -1,161 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_TIME; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AltbnTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/altbn.sol"; - String contractName = "AltBn128"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from 500 to 150") - public void bn256addTest001() { - - String methodStr = "callBn256Add(bytes32,bytes32,bytes32,bytes32)"; - String data = "" - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\"," - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\""; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - - Assert.assertEquals(0,option.getResultValue()); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from 40000 to 6000") - public void bn256ScalarMulTest001() { - String methodStr = "callBn256ScalarMul(bytes32,bytes32,bytes32)"; - String data = "" - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\"," - + "\"0000000000000000000000000000000000000000000000000000000000000001\""; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - - Assert.assertEquals(0,option.getResultValue()); - Assert.assertTrue(energyCost < 40000L); - Assert.assertTrue(energyCost > 6000L); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from ( 80000 * pairNum + 100000)" - + "to ( 34000 * pairNum + 45000) ") - public void bn256paringTest001() { - String methodStr = "callBn256Pairing(bytes)"; - String data = "" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000180" - + "1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59" - + "3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41" - + "209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7" - + "04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678" - + "2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d" - + "120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550" - + "111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c" - + "2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411" - + "198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2" - + "1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed" - + "090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b" - + "12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, true, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - if (option.getResultValue() == 1) { - Assert.assertEquals(option.getReceipt().getResult(), OUT_OF_TIME); - return; - } - - Assert.assertEquals(0,option.getResultValue()); - Assert.assertTrue(energyCost < 80000L * 2 + 100000L); - Assert.assertTrue(energyCost > 34000L * 2 + 45000L); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java deleted file mode 100644 index f9770923984..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class ChainidAndSelfBalance001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/chainid001.sol"; - String contractName = "IstanbulTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 123456789L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = true, description = "chainId should be block zero`s Hash") - public void chainidTest001() { - String methodStr = "getId()"; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, "#", - false, 0, maxFeeLimit, "0", 0, testAddress001, testKey001, blockingStubFull); - - String chainIdHex = ByteArray.toHexString(returns.getConstantResult(0).toByteArray()); - - BlockExtention blockZero = PublicMethed.getBlock2(0, blockingStubFull); - String tem = ByteArray.toHexString(blockZero.getBlockid().toByteArray()).substring(56); - String blockZeroId = "00000000000000000000000000000000000000000000000000000000" + tem; - - Assert.assertEquals(chainIdHex, blockZeroId); - } - - /* - * New command selfBalance for solidity compiler, - * optimize address.balance when contract`s balance - */ - - @Test(enabled = true, description = "selfBalance of addres(this).balance") - public void getBalanceTest001() { - - String methodStr = "getBalance()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long contractBalance = PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(contractBalance, getBalance); - - } - - - @Test(enabled = true, description = "selfBalance of contractAddress") - public void getBalanceTest002() { - - String methodStr = "getBalance(address)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long contractBalance = PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(contractBalance, getBalance); - - } - - @Test(enabled = true, description = "selfBalance of normal Address") - public void getBalanceTest003() { - String methodStr = "getBalance(address)"; - String argsStr = "\"" + Base58.encode58Check(testFoundationAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long accountBalance = PublicMethed - .queryAccount(testFoundationAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(accountBalance, getBalance); - - } - - @Test(enabled = true, description = "selfBalance of unActive Address") - public void getBalanceTest004() { - String methodStr = "getBalance(address)"; - - byte[] unActiveAddress = new ECKey(Utils.getRandom()).getAddress(); - - String argsStr = "\"" + Base58.encode58Check(unActiveAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(0, getBalance.longValue()); - - } - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java deleted file mode 100644 index 9f6d87cf3af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java +++ /dev/null @@ -1,105 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class Create2IstanbulTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/create2Istanbul.sol"; - String contractName = "create2Istanbul"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - /** - * Create2 Algorithm Changed - * Before: according to msg.sender`s Address, salt, bytecode to get create2 Address - * After : according to contract`s Address, salt, bytecode to get create2 Address - * The calculated Create2 address should be same as get(bytes1,bytes,uint256) - */ - - @Test(enabled = true, description = "create2 Algorithm Change") - public void create2IstanbulTest001() { - String filePath = "src/test/resources/soliditycode/create2Istanbul.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methodStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + "1"; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argStr, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - String returnHex = ByteArray.toHexString(option.getContractResult(0).toByteArray()); - - Assert.assertEquals(0,option.getResultValue()); - - String methodStr2 = "get(bytes1,bytes,uint256)"; - String argStr2 = "\"41\",\"" + code + "\"," + 1; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr2, argStr2, - false, 0, - maxFeeLimit, "0", 0, testAddress001, testKey001, blockingStubFull); - String getHex = ByteArray.toHexString(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(returnHex,getHex); - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java deleted file mode 100644 index 6b8b21a29c5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java +++ /dev/null @@ -1,269 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AbiEncodeTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/abiencode.sol"; - String contractName = "AbiEncode"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("abi:" + abi); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test02TriggerContract() { - String methodStr = "h(int256[2][])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000000200000000000000" - + "000000000000000000000000000000000000000000000000003000000000000000000000000000000000000" - + "000000000000000000000000000300000000000000000000000000000000000000000000000000000000000" - + "000040000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000006300000000000000000000000000000000000000000" - + "000000000000000000000060000000000000000000000000000000000000000000000000000000000000008"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000100000000000000000000000000000000000000" - + "00000000000000000000000000200000000000000000000000000000000000000000000000000000000" - + "00000000300000000000000000000000000000000000000000000000000000000000000030000000000" - + "00000000000000000000000000000000000000000000000000000400000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000630000000000000000000000000000000000000000000000000000000000000006000" - + "0000000000000000000000000000000000000000000000000000000000008", - contractResult); - - String methodStr1 = "i(int256[2][2])"; - String argStr1 = "0000000000000000000000000000000000000000000000000000000000000005000000000000" - + "000000000000000000000000000000000000000000000000000700000000000000000000000000000000000" - + "000000000000000000000000003e80000000000000000000000000000000000000000000000000000000000" - + "000065"; - String txid1 = PublicMethed.triggerContract(contractAddress, methodStr1, argStr1, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000080000000000000000000000000000000000000" - + "00000000000000000000000000050000000000000000000000000000000000000000000000000000000" - + "00000000700000000000000000000000000000000000000000000000000000000000003e80000000000" - + "000000000000000000000000000000000000000000000000000065", - contractResult1); - } - - @Test(enabled = true, description = "Trigger contract with negative number") - public void test03TriggerContract() { - String methodStr = "h(int256[2][])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000000200000000000000" - + "000000000000000000000000000000000000000000000000003ffffffffffffffffffffffffffffffffffff" - + "ffffffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000000" - + "000090000000000000000000000000000000000000000000000000000000000000042ffffffffffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffbe00000000000000000000000000000000000000000" - + "000000000000000000000b1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa8"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000100000000000000000000000000000000000000" - + "00000000000000000000000000200000000000000000000000000000000000000000000000000000000" - + "000000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000" - + "00000000000000000000000000000000000000000000000000000900000000000000000000000000000" - + "00000000000000000000000000000000042ffffffffffffffffffffffffffffffffffffffffffffffff" - + "ffffffffffffffbe00000000000000000000000000000000000000000000000000000000000000b1fff" - + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa8", - contractResult); - - String methodStr1 = "i(int256[2][2])"; - String argStr1 = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000" - + "000000000000000000000000000000000000000000000000000900000000000000000000000000000000000" - + "00000000000000000000000000042ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "ffffbe"; - String txid1 = PublicMethed.triggerContract(contractAddress, methodStr1, argStr1, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "00000000000000000000000000000000000000000000000000000000000000200000000000000000" - + "000000000000000000000000000000000000000000000080ffffffffffffffffffffffffffffffffff" - + "ffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000" - + "0000000000090000000000000000000000000000000000000000000000000000000000000042ffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffbe", - contractResult1); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java deleted file mode 100644 index 63aaa9ae313..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AbstractTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "compile abstract contract 001") - public void test01CompileAbstractContract001() { - String filePath = "./src/test/resources/soliditycode/abstract001.sol"; - String contractName = "abstract001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - Assert.assertTrue(abi.length() > 0); - Assert.assertTrue(code.length() == 0); - } - - @Test(enabled = true, description = "compile abstract contract 002") - public void test02CompileAbstractContract002() { - String filePath = "./src/test/resources/soliditycode/abstract002.sol"; - String contractName = "abstract002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - Assert.assertTrue(abi.length() > 0); - Assert.assertTrue(code.length() == 0); - } - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java deleted file mode 100644 index d537f06ebd6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AddressChange { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] contractAddressOld = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/getAddressChange.sol"; - String contractName = "getAddressChange"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_getAddressChange"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_getAddressChange"); - contractName = "getAddressChangeOldVersion"; - contractAddressOld = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get external function address") - public void test01GetExternalAddress() { - String txid = ""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testaddress1()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - byte[] b1 = new byte[21]; - b1[0] = 0x41; - System.arraycopy(result, 12, b1, 1, 20); - Assert.assertEquals(Base58.encode58Check(contractAddress), Base58.encode58Check(b1)); - } - - @Test(enabled = true, description = "get external function address, solidity version < 0.6.0") - public void test02GetExternalAddressOldVersion() { - String txid = ""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressOld, "testaddress1()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - byte[] b1 = new byte[21]; - b1[0] = 0x41; - System.arraycopy(result, 12, b1, 1, 20); - Assert.assertEquals(Base58.encode58Check(contractAddressOld), Base58.encode58Check(b1)); - } - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed - .freedResource(contractAddressOld, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java deleted file mode 100644 index 990d8f44c59..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java +++ /dev/null @@ -1,249 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AssignToExternalTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/AssignToExternal.sol"; - String contractName = "AssignToExternal"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test02TriggerContract() { - String methodStr = "f(uint256)"; - String argStr = "2"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - int contractResult = - ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(3, contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test03TriggerContract() { - String methodStr = "StringSet(string)"; - String argStr = "\"test\""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "7465737400000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test04TriggerContract() { - String methodStr = "ByteSet(bytes32)"; - String argStr = "00000000000000000000000000000000000000000000000000000000000003e9"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - int contractResult = - ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(1001, contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test05TriggerContract() { - String methodStr = "UintArraySet(uint256[2])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000003e9" - + "00000000000000000000000000000000000000000000000000000000000003e9"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("00000000000000000000000000000000000000000000000000000000000003e9" - + "00000000000000000000000000000000000000000000000000000000000003e9", contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test06TriggerContract() { - String methodStr = "AddSet(address)"; - String argStr = "\"TYVT8YJYis13NdrzdE7yVuwVxjsaRy2UsM\""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("000000000000000000000000f70b0a56acf4b0af44723c329ff113a677b5f589", - contractResult); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java deleted file mode 100644 index febc9cbe63c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class BlockhashTest { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/BlockHash.sol"; - String contractName = "TestBlockHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "BlockHash should not be change after command OR") - public void test01BlockHashWithOR() { - String methodStr = "testOR1(bytes32)"; - String argStr = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before OR should equals to blockHash after OR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testOR2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before OR should equals to blockHash after OR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - - @Test(enabled = true, description = "BlockHash should not be change after command AND") - public void test02BlockHashWithAND() { - String methodStr = "testAND1(bytes32)"; - String argStr = "0000000000000000000000000000000000000000000000000000000000000000"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before AND should equals to blockHash after AND - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testAND2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before AND should equals to blockHash after AND - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - - @Test(enabled = true, description = "BlockHash should not be change after command XOR") - public void test03BlockHashWithXOR() { - String methodStr = "testXOR1(bytes32)"; - String argStr = "00000000000000000000000000000000ffffffffffffffffffffffffffffffff"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before XOR should equals to blockHash after XOR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testXOR2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before XOR should equals to blockHash after XOR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java deleted file mode 100644 index 52f1eb6b80a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CallValueGasPureTest { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - } - - @Test(enabled = true, description = "call.value.gas be pure") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(testAddress001, 1000_000_000L, foundationAddress001, foundationKey001, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(foundationAddress001, 100_000_000L, 0, 0, - ByteString.copyFrom(testAddress001), foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(testAddress001, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/callValueGasPure.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 0, - 10000, "0", 0, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String param = "\"" + Base58.encode58Check(testAddress001) + "\""; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "check(address)", - param, false, 0, 1000000000L, "0", 0, testAddress001, - testKey001, blockingStubFull); - - Assert.assertNotNull(extention); - Assert.assertTrue(extention.hasResult()); - Assert.assertTrue(extention.getResult().getResult()); - - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(foundationAddress001, balance, testAddress001, testKey001, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java deleted file mode 100644 index 296f8a36b44..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CallvalueTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 3147483647L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/callvalue.sol"; - String contractName = "Callvalue"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract") - public void test02TriggerContract() { - String methodStr = "check()"; - // 15 - String triggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - 15, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - logger.info("contractResult:" + contractResult); - Assert.assertEquals(Long.parseLong(contractResult, 16), 15); - - // 0 - String triggerTxid1 = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - logger.info("contractResult1:" + contractResult1); - Assert.assertEquals(Long.parseLong(contractResult1, 16), 0); - - // Integer.MAX_VALUE - String triggerTxid2 = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - Integer.MAX_VALUE, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - if (infoById2.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById2.get().getResMessage()); - } - logger.info("infoById2" + infoById2); - String contractResult2 = - ByteArray.toHexString(infoById2.get().getContractResult(0).toByteArray()); - logger.info("contractResult2:" + contractResult2); - Assert.assertEquals(Long.parseLong(contractResult2, 16), Integer.MAX_VALUE); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java deleted file mode 100644 index bd6ad18c451..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java +++ /dev/null @@ -1,255 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerconstantContract trigger modidy storage date") - public void testConstantCallStorage001() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "NotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setnum()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - logger.info("transactionExtention: " + transactionExtention); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract ") - public void testConstantCallStorage002() { - - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract " - + "view function, use 0.5.* version solidity complier") - public void testConstantCallStorage003() { - String filePath = "src/test/resources/soliditycode/constantCallStorage002.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertFalse(transactionExtention.getResult().getResult()); - Assert.assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("Not enough energy")); - } - - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract " - + "view function, use 0.4.* version solidity complier") - public void testConstantCallStorage004() { - String filePath = "src/test/resources/soliditycode/constantCallStorage002.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java deleted file mode 100644 index 6e838b17bb4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java +++ /dev/null @@ -1,421 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerconstantContract trigger modidy storage date with " - + "difference date type") - public void testConstantCallStorage001() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "viewCall"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - // modify bool type - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBool(bool)", "true", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBool()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(0, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify NegativeInt type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeNegativeInt(int256)", "-2", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(-2, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getNegativeInt()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(-32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify address type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeAddress(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - String ContractResult = - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - String tmpAddress = - Base58.encode58Check(ByteArray.fromHexString("41" + ContractResult.substring(24))); - Assert.assertEquals(WalletClient.encode58Check(contractAddress), tmpAddress); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getAddress()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000dcad3a6d3569df655070ded06cb7a1b2ccd1d3af", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify byte32s type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBytes32(bytes32)", "\"0xdCad3a6d3569DF655070DEd1\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("dcad3a6d3569df655070ded10000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBytes32()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000dcad3a6d3569df655070ded0", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify bytes type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBytes(bytes)", "\"0x05\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0500000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBytes()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify string type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeString(string)", "\"321test\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("321test", - ByteArray.toStr(transactionExtention - .getConstantResult(0).substring(64, 64 + 7).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getString()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("123qwe", - ByteArray.toStr(transactionExtention - .getConstantResult(0).substring(64, 64 + 6).toByteArray())); - - // modify enum type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeActionChoices(uint8)", "3", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(3, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getActionChoices()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify Int64NegativeArray type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt64NegativeArray(int64[])", - "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt64NegativeArray()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify Int32Array[2][] type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt32Array(int32[2][])", - "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006" - + "0000000000000000000000000000000000000000000000000000000000000007" - + "0000000000000000000000000000000000000000000000000000000000000008" - + "0000000000000000000000000000000000000000000000000000000000000009" - + "000000000000000000000000000000000000000000000000000000000000000a", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006" - + "0000000000000000000000000000000000000000000000000000000000000007" - + "0000000000000000000000000000000000000000000000000000000000000008" - + "0000000000000000000000000000000000000000000000000000000000000009" - + "000000000000000000000000000000000000000000000000000000000000000a", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt32Array()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify Int256Array[2][2] type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt256Array(int256[2][2])", - - "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt256Array()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000000b" - + "0000000000000000000000000000000000000000000000000000000000000016" - + "0000000000000000000000000000000000000000000000000000000000000021" - + "000000000000000000000000000000000000000000000000000000000000002c", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify mapping type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setMapping(uint256)", "55", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(55, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "mapa(address)", "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(34, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java deleted file mode 100644 index 44e1fe2635f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java +++ /dev/null @@ -1,462 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage0425 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Deploy contract without abi") - public void test01DeployContract() { - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/constantCallStorage0425.sol"; - String contractName = "constantCall"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, "[]", code, "", - maxFeeLimit, 0L, 0, 1000000000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = false, description = "Trigger contract constant function without ABI") - public void test02TriggerContract() { - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "changeBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getLog(0).getData().toByteArray())); - - String triggerTxid2 = PublicMethed - .triggerContract(contractAddress, "getBool()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertEquals(0, infoById1.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getLog(0).getData().toByteArray())); - } - - @Test(enabled = false, description = "TriggerConstantContract bool constant function") - public void test03TriggerConstantContract() { - // bool - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBool(bool)", "false", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBool()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // int - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt(int256)", "30", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(30, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // negative int - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeNegativeInt(int256)", "-111", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(-111, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getNegativeInt()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(-32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // uint - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeUint(uint256)", "1024", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(1024, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getUint()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(23487823, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // address - String param = "\"" + Base58.encode58Check(dev001Address) + "\""; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeAddress(address)", param, - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals(Base58.encode58Check(dev001Address), - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getAddress()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - // bytes32 - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBytes32(bytes32)", - "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a", - true, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBytes32()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // bytes - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBytes(bytes)", "\"0x06\"", - false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000106000000000000000000000000000000000000" - + "00000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBytes()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000900000000000000000000000000000000000000" - + "00000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // string - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeString(string)", - "\"1q2w\"", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000043171327700000000000000" - + "000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getString()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000063132337177650000000000" - + "000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // enum - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeActionChoices(uint8)", - "1", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getActionChoices()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int64[] include negative number - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt64NegativeArray(int64[])", - "0000000000000000000000000000000000000000000000000000000000000020000000000000000" - + "00000000000000000000000000000000000000000000000040000000000000000000000000000000" - + "00000000000000000000000000000000b00000000000000000000000000000000000000000000000" - + "00000000000000063000000000000000000000000000000000000000000000000000000000000004" - + "1000000000000000000000000000000000000000000000000000000000000005a", - true, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000040000000000000000000000" - + "00000000000000000000000000000000000000000b000000000000000000000000000000000000000000" - + "000000000000000000006300000000000000000000000000000000000000000000000000000000000000" - + "41000000000000000000000000000000000000000000000000000000000000005a", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt64NegativeArray()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000030000000000000000000000" - + "00000000000000000000000000000000000000005b000000000000000000000000000000000000000000" - + "000000000000000000000200000000000000000000000000000000000000000000000000000000000001" - + "4d", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int32[2][] - String argsStr = - "0000000000000000000000000000000000000000000000000000000000000020000000000000000" - + "00000000000000000000000000000000000000000000000030000000000000000000000000000000" - + "00000000000000000000000000000000d00000000000000000000000000000000000000000000000" - + "00000000000000058fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "70000000000000000000000000000000000000000000000000000000000000022000000000000000" - + "0000000000000000000000000000000000000000000000063fffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffc8"; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt32Array(int32[2][])", - argsStr, true, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(argsStr, - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt32Array()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000030000000000000000000000" - + "000000000000000000000000000000000000000001000000000000000000000000000000000000000000" - + "000000000000000000000200000000000000000000000000000000000000000000000000000000000000" - + "030000000000000000000000000000000000000000000000000000000000000004000000000000000000" - + "000000000000000000000000000000000000000000000500000000000000000000000000000000000000" - + "00000000000000000000000006", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int256[2][2] - String argsStr1 = - "0000000000000000000000000000000000000000000000000000000000000013000000000000000" - + "00000000000000000000000000000000000000000000000440000000000000000000000000000000" - + "000000000000000000000000000000037fffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffde"; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt256Array(int256[2][2])", - argsStr1, true, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(argsStr1, - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt256Array()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000b00" - + "000000000000000000000000000000000000000000000000000000000000160000000000000000000000" - + "000000000000000000000000000000000000000021000000000000000000000000000000000000000000" - + "000000000000000000002c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify mapping type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setMapping(uint256)", "39", - false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(39, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "mapa(address)", "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"", false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(88, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java deleted file mode 100644 index 5633f0ff936..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java +++ /dev/null @@ -1,539 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class EthGrammer { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - byte[] contractC = null; - byte[] contractD = null; - byte[] create2Address; - String create2Str; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/EthGrammer.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractC = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractC, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - contractName = "D"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractD = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractD, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "test get base fee value = commit.No 11 energy fee") - public void test01baseFee() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "baseFee()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long basefee = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("basefee: " + basefee); - long energyfee; - Protocol.ChainParameters chainParameters = blockingStubFull - .getChainParameters(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - String key = ""; - boolean flag = false; - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - key = getChainParameters.get().getChainParameter(i).getKey(); - if ("getEnergyFee".equals(key)) { - energyfee = getChainParameters.get().getChainParameter(i).getValue(); - logger.info("energyfee: " + energyfee); - Assert.assertEquals(basefee, energyfee); - flag = true; - } - } - Assert.assertTrue(flag); - } - - @Test(enabled = true, description = "test get gas price value = commit.No 11 energy fee") - public void test02GasPrice() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "gasPrice()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get create2 address, test get base fee ") - public void test03BaseFeeFromCreate2() { - String methedStr = "deploy(uint256)"; - String argsStr = "1"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(create2Address, - "baseFeeOnly()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long basefee = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("basefee: " + basefee); - long energyfee; - Protocol.ChainParameters chainParameters = blockingStubFull - .getChainParameters(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - String key = ""; - boolean flag = false; - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - key = getChainParameters.get().getChainParameter(i).getKey(); - if ("getEnergyFee".equals(key)) { - energyfee = getChainParameters.get().getChainParameter(i).getValue(); - logger.info("energyfee: " + energyfee); - Assert.assertEquals(basefee, energyfee); - flag = true; - } - } - Assert.assertTrue(flag); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(create2Address, - "gasPriceOnly()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long gasprice = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("gasprice: " + gasprice); - Assert.assertEquals(basefee, gasprice); - } - - @Test(enabled = true, description = "call can use 63/64 energy in new contract") - public void test04CallEnergy() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - String methedStr = "testCall(address,address)"; - String argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - String txid = PublicMethed.triggerContract(contractC, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - logger.info("testAccount: " + testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address call can use 63/64 energy in new contract") - public void test05Create2AddressCallEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "2"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testCall(address,address)"; - argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address delegatecall " - + "can use 63/64 energy in new contract") - public void test06Create2AddressDelegateCallEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "5"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testDelegateCall(address,address)"; - argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address this.function " - + "can use 63/64 energy in new contract") - public void test07Create2AddressCallFunctionEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "6"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testCallFunctionInContract(address)"; - argsStr = "\"" + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - // - @Test(enabled = true, description = "test get Ripemd160 input is 123") - public void test08getRipemd160() { - String args = "\"123\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("e3431a8e0adbf96fd140103dc6f63a3f8fa343ab000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is empty") - public void test09getRipemd160() { - String args = "\"\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("9c1185a5c5e9fc54612808977ee8f548b2258d31000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input length is greater than 256") - public void test10getRipemd160() { - String args = "\"111111111111ddddddddddddd0x0000000000000000000000008b56a0602cc81fb0" - + "b99bce992b3198c0bab181ac111111111111ddddddddddddd0x0000000000000000000000008b56" - + "a0602cc81fb0b99bce992b3198c0bab181ac%^$#0000008b56a0602cc81fb0b99bce99" - + "2b3198c0bab181ac%^$#0000008b56a0602cc81fb0b99bce992b3198c0bab181ac%^$#\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("173c283ebcbad0e1c623a5c0f6813cb663338369000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is string " - + "and do not convert to bytes") - public void test11getRipemd160Str() { - String args = "\"data\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160Str(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("cd43325b85172ca28e96785d0cb4832fd62cdf43000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is string and " - + "do not convert to bytes") - public void test12getRipemd160Str() { - String args = "\"000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160Str(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("efe2df697b79b5eb73a577251ce3911078811fa4000000000000000000000000", result); - } - - @Test(enabled = true, description = "test blake2f") - public void test13getBlak2f() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "callF()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac" - + "4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923", - result); - - } - - @Test(enabled = true, description = "when call create2, stack depth will be checked" - + "if stack depth is greater than 64, then create command will revert" - + "but run environment can not compute so much, so the actual result is time out") - public void test14FixCreate2StackDepth() { - String methedStr = "fixCreate2StackDepth(uint256)"; - String argsStr = "123"; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention.toString()); - String message = ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()); - Assert.assertTrue(message.contains("CPU timeout")); - /*int interCount = transactionExtention.getInternalTransactionsCount(); - int createCount = 0; - for(int i=0;i= 15 && createCount <= 64);*/ - } - - @Test(enabled = true, description = "when call create, stack depth will be checked." - + "if stack depth is greater than 64, then create command will revert" - + "but run environment can not compute so much, so the actual result is time out") - public void test15FixCreateStackDepth() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - "fixCreateStackDepth()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String message = ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()); - logger.info("transactionExtention: " + transactionExtention.toString()); - Assert.assertTrue(message.contains("CPU timeout")); - /*int interCount = transactionExtention.getInternalTransactionsCount(); - int createCount = 0; - for(int i=0;i= 15 && createCount <= 64);*/ - - } - - @Test(enabled = false, description = "test max Energy Limit For trigger Constant contract") - public void test16MaxEnergyLimitForConstant() { - String methedStr = "transfer(address)"; - String argsStr = "\"" + Base58.encode58Check(testNetAccountAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("transactionExtention: " + transactionExtention.toString()); - } - - @Test(enabled = true, description = "commit NO.47 value can be 1e17 if commit No.63 opened") - public void test17Commit47Value() { - HashMap proposalMap = new HashMap(); - proposalMap.put(47L, 100000000000000000L); - org.testng.Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java deleted file mode 100644 index 10b47c7793f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java +++ /dev/null @@ -1,556 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class EthGrammer02 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractD = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - int salt = 11; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/EthGrammer02.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractD = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractD, - blockingStubFull); - Assert.assertEquals(1, smartContract.getVersion()); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef") - public void test16forbiddenBytecodeStartWithEf() { - String code = "60ef60005360016000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", - abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef00") - public void test17forbiddenBytecodeStartWithEf() { - String code = "60ef60005360026000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", - abi, code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef0000") - public void test18forbiddenBytecodeStartWithEf() { - String code = "60ef60005360036000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode" - + " ef00000000000000000000000000000000000000000000000000000000000000") - public void test19forbiddenBytecodeStartWithEf() { - String code = "60ef60005360206000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can deploy contract with bytecode fe") - public void test20forbiddenBytecodeStartWithEf() { - String code = "60fe60005360016000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef") - public void test21forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360016000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef00") - public void test22forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360026000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef0000") - public void test23forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360036000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode " - + "ef00000000000000000000000000000000000000000000000000000000000000") - public void test24forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360206000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can deploy contract by create with bytecode fe") - public void test25forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60fe60005360016000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef") - public void test26forbiddenBytecodeStartWithEf() { - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360016000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef00") - public void test27forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360026000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef0000") - public void test28forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360036000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode " - + "ef00000000000000000000000000000000000000000000000000000000000000") - public void test29forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360206000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can deploy contract by create2 with bytecode fe") - public void test30forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60fe60005360016000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not sendcoin to contract") - public void test31forbiddenSendTrxToContract() { - Assert.assertFalse(PublicMethed - .sendcoin(contractD, 100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - } - - @Test(enabled = true, description = "db key can use high 16 bytes," - + "0x6162630000000000000000000000000000000000000000000000000000000000") - public void test32DbKeyUseHigh16Bytes() { - String slot = "0x6162630000000000000000000000000000000000000000000000000000000000"; - long value = 121; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes all f," - + "0xffffffffffffffffffffffffffffffff00000000000000000000000000000000") - public void test33DbKeyUseHigh16Bytes() { - String slot = "0xffffffffffffffffffffffffffffffff00000000000000000000000000000000"; - long value = 122; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes 1," - + " 0x0000000000000000000000000000000100000000000000000000000000000000") - public void test34DbKeyUseHigh16Bytes() { - String slot = "0x0000000000000000000000000000000100000000000000000000000000000000"; - long value = 123; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes all 0,low 16bytes 1." - + " 0x0000000000000000000000000000000000000000000000000000000000000001") - public void test35DbKeyUseHigh16Bytes() { - String slot = "0x0000000000000000000000000000000000000000000000000000000000000001"; - long value = 124; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot all 0," - + " 0x0000000000000000000000000000000000000000000000000000000000000000") - public void test36DbKeyUseHigh16BytesAllBytes0() { - String slot = "0x0000000000000000000000000000000000000000000000000000000000000000"; - long value = 125; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot all f," - + " 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") - public void test37DbKeyUseHigh16BytesAllBytesF() { - String slot = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - long value = 126; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "TransactionExtention has logs and internal_transactions") - public void test38ConstantLogEven() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60fe60005360016000f3\"," + salt; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, transactionExtention.getLogsCount()); - Assert.assertEquals(1, transactionExtention.getInternalTransactionsCount()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java deleted file mode 100644 index cd31d1f6826..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class FixbugTest086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = - "src/test/resources/soliditycode/abstractContractWithMapParamsConstructor.sol"; - String contractName = "Cat"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "abstract With Map Params") - public void test01ContractWithMapParams() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "getMapValue()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(20, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - @Test(enabled = true, description = " super skip unimplemented in abstract contract") - public void test02SkipUnimplemented() { - String filePath = - "src/test/resources/soliditycode/super_skip_unimplemented_in_abstract_contract.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "f()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(42, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java deleted file mode 100644 index 9977fc94cc8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class FunctionArray2Storage086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/function_type_array_to_storage.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "function array test view to default") - public void test01View2Default() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testViewToDefault()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(12, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(22, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - } - - @Test(enabled = true, description = "function array pure to default") - public void test02Pure2Default() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testPureToDefault()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(13, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(23, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - - } - - @Test(enabled = true, description = "function array pure to view ") - public void test03Pure2View() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testPureToView()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(13, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(23, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java deleted file mode 100644 index 2f7950ed5d9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java +++ /dev/null @@ -1,285 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class LengthTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/arrayLength001.sol"; - String contractName = "arrayLength"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "push() increase Array length") - public void arrayLengthTest001() { - - String methodStr = "arrayPush()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push(value) increase Array length") - public void arrayLengthTest002() { - - String methodStr = "arrayPushValue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0100000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "pop() decrease Array length") - public void arrayLengthTest003() { - - String methodStr = "arrayPop()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push() return no value") - public void arrayLengthTest004() { - - String methodStr = "arrayPushReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push(value) return value") - public void arrayLengthTest005() { - - String methodStr = "arrayPushValueReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "pop() return no value") - public void arrayLengthTest006() { - - String methodStr = "arrayPopReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes push() return value") - public void arrayLengthTest007() { - - String methodStr = "bytesPush()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes push(value) return no value") - public void arrayLengthTest008() { - - String methodStr = "bytesPushValue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes pop() return no value") - public void arrayLengthTest009() { - - String methodStr = "bytesPop()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - @Test(enabled = true, description = "array length change before v0.5.15") - public void arrayLengthV0515() { - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_arrayLenth_0.5.15"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_arrayLength_0.5.15"); - String contractName = "arrayLength"; - byte[] v0515Address = PublicMethed.deployContract(contractName,abi,code,"",maxFeeLimit,0,100, - null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String Txid = PublicMethed.triggerContract(v0515Address,"ChangeSize()","",false,0,maxFeeLimit, - testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(Txid, blockingStubFull); - - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0100000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java deleted file mode 100644 index 4527a8d63bf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MappingFixTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - // after solidity version 0.5.4. - // Tron Solidity compiler is no longer compatible with Ethereum - // Tron handles 41 Address in contract, and Ethereum do not - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/SolidityMappingFix.sol"; - String contractName = "Tests"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "Trigger contract,set balances[msg.sender]") - public void test02TriggerContract() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String methodStr = "update(uint256)"; - String argStr = "123"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - TransactionInfo transactionInfo = infoById.get(); - logger.info("infoById" + infoById); - - String ContractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - String tmpAddress = - Base58.encode58Check(ByteArray.fromHexString("41" + ContractResult.substring(24))); - Assert.assertEquals(WalletClient.encode58Check(dev001Address), tmpAddress); - - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - methodStr = "balances(address)"; - argStr = "\"" + WalletClient.encode58Check(dev001Address) + "\""; - TransactionExtention return1 = PublicMethed - .triggerContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, "0", 0L, dev001Address, dev001Key, blockingStubFull); - logger.info("return1: " + return1); - logger.info(Hex.toHexString(return1.getConstantResult(0).toByteArray())); - int ContractRestult = ByteArray.toInt(return1.getConstantResult(0).toByteArray()); - - Assert.assertEquals(123, ContractRestult); - - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java deleted file mode 100644 index 6d80a266d5e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MappingPopingTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/TestMappings_array_pop.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract ") - public void test02TriggerContract() { - String methodStr = "n1(uint256,uint256)"; - String argStr = "1,1001"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - } - - @Test(enabled = true, description = "Trigger contract ") - public void test03TriggerContract() { - String methodStr = "p()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java deleted file mode 100644 index 13e676401ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class NegativeArrayTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/negativeArray.sol"; - String contractName = "NegativeArray"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract") - public void test02TriggerContract() { - // get[2] - String methodStr = "get(uint256)"; - String argStr = "2"; - String triggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - logger.info("contractResult:" + contractResult); - Assert.assertEquals(new BigInteger(contractResult, 16).intValue(), -3); - - // get[1] - String argStr1 = "1"; - String triggerTxid1 = PublicMethed.triggerContract(contractAddress, methodStr, argStr1, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - logger.info("contractResult1:" + contractResult1); - Assert.assertEquals(new BigInteger(contractResult1, 16).intValue(), 2); - - // change array value - String triggerTxid2 = PublicMethed.triggerContract(contractAddress, "set()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - if (infoById2.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById2.get().getResMessage()); - } - logger.info("infoById2" + infoById2); - String log1 = - ByteArray.toHexString(infoById2.get().getLog(0).getData().toByteArray()); - logger.info("log1:" + log1); - Assert.assertEquals(new BigInteger(log1, 16).intValue(), -1); - String log2 = ByteArray.toHexString(infoById2.get().getLog(1).getData().toByteArray()); - logger.info("log2:" + log2); - Assert.assertEquals(new BigInteger(log2, 16).intValue(), 3); - String log3 = - ByteArray.toHexString(infoById2.get().getLog(2).getData().toByteArray()); - logger.info("log3:" + log3); - Assert.assertEquals(new BigInteger(log3, 16).intValue(), -8); - - // get[2] - String triggerTxid3 = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - if (infoById3.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById3.get().getResMessage()); - } - logger.info("infoById3" + infoById3); - String contractResult3 = - ByteArray.toHexString(infoById3.get().getContractResult(0).toByteArray()); - logger.info("contractResult3:" + contractResult3); - Assert.assertEquals(new BigInteger(contractResult3, 16).intValue(), -8); - - // get[1] - String triggerTxid4 = PublicMethed.triggerContract(contractAddress, methodStr, argStr1, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById4 = PublicMethed - .getTransactionInfoById(triggerTxid4, blockingStubFull); - if (infoById4.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById4.get().getResMessage()); - } - logger.info("infoById4" + infoById4); - String contractResult4 = - ByteArray.toHexString(infoById4.get().getContractResult(0).toByteArray()); - logger.info("contractResult4:" + contractResult4); - Assert.assertEquals(new BigInteger(contractResult4, 16).intValue(), 3); - - // get[3] - String triggerTxid5 = PublicMethed.triggerContract(contractAddress, methodStr, "3", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - logger.info("infoById5" + infoById5); - Assert.assertEquals(1, infoById5.get().getResultValue()); - Assert.assertEquals("REVERT opcode executed", infoById5.get() - .getResMessage().toStringUtf8()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java deleted file mode 100644 index 527dfcfdd9f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java +++ /dev/null @@ -1,269 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class NewFeatureForSolc068 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] getSelectorContract = null; - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature068.sol"; - String contractName = "testMapKey"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "map with enum key") - public void test01MapWithEnumKey() { - String txid = PublicMethed.triggerContract(mapKeyContract, - "setEnumValue(uint256)", "1", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "map with contract key") - public void test02MapWithContractKey() { - - String txid = PublicMethed.triggerContract(mapKeyContract, - "setContractValue()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getContractValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(2, trueRes); - } - - @Test(enabled = true, description = "get function selector during compile period") - public void test03GetSelectorDuringCompile() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getfunctionSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("trueRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.startsWith("48593bae")); - } - - @Test(enabled = true, description = "test storage variable init before been used") - public void test04StorageValInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testStorage()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = PublicMethed - .getContractStringMsg(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("test", trueRes); - } - - @Test(enabled = true, description = "test immutable variable inited when declared") - public void test05ImmutableInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getOwner()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(ByteArray.toHexString(PublicMethed - .getFinalAddress(contractExcKey)).substring(2), trueRes.substring(24)); - - } - - @Test(enabled = true, description = "test immutable variable inited in construct") - public void test06ImmutableInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getImmutableVal()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(5, trueRes); - } - - @Test(enabled = true, description = "get interface id," - + "interface id is result of all function selector's XOR ") - public void test07GetInterfaceId() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getInterfaceId()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(ByteArray.subArray(result, 0, 4)); - String trueRes1 = ByteArray.toHexString(ByteArray.subArray(result, 32, 36)); - - logger.info("truerRes: " + trueRes + " truerRes1: " + trueRes1 - + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("a9ab72bd", trueRes); - Assert.assertEquals(trueRes, trueRes1); - - } - - @Test(enabled = true, description = "abstract contract can have vitrual modifier with empty body") - public void test08VirtualModifier() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "requireOwner()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - int trueRes = ByteArray.toInt(result); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(6, trueRes); - - } - - @Test(enabled = true, description = "uint256 max and mine") - public void test09Uint256MaxMine() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getUint256MinAndMax()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(ByteArray.subArray(result, 0, 32)); - String trueRes1 = ByteArray.toHexString(ByteArray.subArray(result, 32, 64)); - logger.info("truerRes: " + trueRes + "truerRes1: " + trueRes1 - + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - trueRes); - Assert.assertEquals("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - trueRes1); - - } - - @Test(enabled = true, description = "solidity 0.6.12 test Reference " - + "variable can be marked by calldata") - public void test10CalldataModifier() { - String hexAdd = ByteArray.toHexString(PublicMethed.getFinalAddress(contractExcKey)); - String args = "\"0x" + hexAdd + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "calldataModifier(bytes)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(result); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains(hexAdd)); - } - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java deleted file mode 100644 index 3e55337e60c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java +++ /dev/null @@ -1,133 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class NewFeatureForSolc076 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature076.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "call method outside contract") - public void test01CallOutsideMethod() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getOutsideMethod()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "get abstract contract and interface name") - public void test02GetTypeName() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAbstractName()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toStr(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains("abvd")); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getInterfaceName()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - trueRes = ByteArray.toStr(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains("qwer")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java deleted file mode 100644 index 39820c4f24c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java +++ /dev/null @@ -1,313 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolc080 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature080.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 5000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "math sub without unchecked, transaction revert") - public void test01MathSubNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "subNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "math sub with uncheck,transaction success") - public void test02SubWithUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "subWithUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(255, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertTrue(transactionExtention.getEnergyUsed() > 300); - - } - - @Test(enabled = true, description = "math add overflow without unchecked, transaction revert") - public void test03MathAddNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "addNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "math divide zero without unchecked, transaction revert") - public void test04DivideZeroNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "divideZeroNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "assert fail without unchecked, transaction revert") - public void test05AssertFailNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "assertFailNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "array out of index without unchecked, transaction revert") - public void test06AssertFailNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "arrayOutofIndex()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "type convert") - public void test07TypeConvert() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "typeConvert()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(65535, trueRes); - Assert.assertEquals(true, - transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi by default turn: right to left") - public void test08PowerMultiRightToLeft() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiRightToLeft()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(2, trueRes); - Assert.assertEquals(true, - transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi: left to right ") - public void test09PowerMultiLeftToRight() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiLeftToRight()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(64, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi with 2 params ") - public void test10PowerMultiWith2Params() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiWith2Params()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(8, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get block chain id ") - public void test11GetBlockChainId() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getBlockChainId()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String chainId = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("chainId: " + chainId); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get normal account address hashcode ") - public void test12GetAccountHashCode() { - String argStr = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAddressCodehash(address)", argStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info(transactionExtention.toString()); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("0000000: " + trueRes); - } - - @Test(enabled = true, description = "get contract address hashcode ") - public void test13GetContractAddressHashCode() { - String argStr = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAddressCodehash(address)", argStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info(transactionExtention.toString()); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("0000000: " + trueRes); - } - - @Test(enabled = true, description = "transfer trx to tx.origin address with payable") - public void test14TransferToTxoriginAddress() { - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance: " + beforeBalance); - - String methodStr = "transferToTxorigin(uint64)"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "1000000", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long afterBalance = info.getBalance(); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance == afterBalance + 1000000); - } - - @Test(enabled = true, description = "transfer trx to literal address with payable") - public void test15TransferToLiteralAddress() { - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance: " + beforeBalance); - - String methodStr = "transferToLiteralAddress(uint64)"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "1000000", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long afterBalance = info.getBalance(); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance == afterBalance + 1000000); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java deleted file mode 100644 index 375323c0d66..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java +++ /dev/null @@ -1,240 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolc0811 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature0811.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Get enum.min or enum.max") - public void test001GetEnumMinOrMax() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumMin()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(0, result); - - - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumMax()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(3, result); - - } - - - @Test(enabled = true,description = "User defined type of data") - public void test002SupportUserDefinedTypeOfData() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getUserDefinedValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(45, result); - } - - - @Test(enabled = true,description = "Get assembly address") - public void test003GetAssemblyAddress() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testGetAddress()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertTrue(ByteArray.toHexString(transactionExtention.getConstantResult(0) - .toByteArray()).contains(ByteArray.toHexString(mapKeyContract).substring(2))); - } - - - @Test(enabled = true,description = "Get assembly selector") - public void test004GetAssemblySelector() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testGetSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(3781905051L, result); - } - - - @Test(enabled = true,description = "Get ABI-Encode calldata") - public void test005GetAbiEncodedCalldata() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "fSignatureFromLiteralCall()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000084" - + "33d8581000000000000000000000000000000000000000000000000000000000" - + "0000000100000000000000000000000000000000000000000000000000000000" - + "0000004000000000000000000000000000000000000000000000000000000000" - + "0000000331323300000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - - @Test(enabled = true,description = "Support constructor read immutable value") - public void test006SupportConstructorReadImmutableValue() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "readX()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(33, result); - - - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "readI()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(33, result); - - - } - - - @Test(enabled = true,description = "Fix immutable symbol bug") - public void test007FixImmutableSymbol() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "fixBugTest()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - Assert.assertEquals("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java deleted file mode 100644 index 30544ef8e64..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java +++ /dev/null @@ -1,305 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class NewFeatureForSolc086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature086.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "catch assert fail") - public void test01TrtCatchAssertFail() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchAssertFail()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, trueRes); - - } - - @Test(enabled = true, description = "catch under flow") - public void test02CatchUnderFlow() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchUnderFlow()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(17, trueRes); - - } - - @Test(enabled = true, description = "catch divide zero") - public void test03CatchDivideZero() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchDivideZero()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(18, trueRes); - } - - @Test(enabled = true, description = "get address code length") - public void test04GetAddressCodeLength() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "getAddressCodeLength()", - "#", false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertTrue(transactionInfo.get().getFee() < 40000); - } - - @Test(enabled = true, description = "fix kecca256 bug: differt length return same code") - public void test05Kecca256BugFix() { - String args = "\"abcd123\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "keccak256Bug(string)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(0, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - logger.info(transactionInfo.toString()); - } - - @Test(enabled = true, description = "revert error type with params") - public void test06RevertErrorType() { - String args = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\",1000000000"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "transfer(address,uint256)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(1, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("cf479181", - ByteArray.toHexString(transactionInfo.get() - .getContractResult(0).substring(0, 4).toByteArray())); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(4, 36).toByteArray())); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000003b9aca00", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(36, 68).toByteArray())); - - } - - @Test(enabled = true, description = "revert error type no params") - public void test07RevertErrorType() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "withdraw()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(1, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("82b42900", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(0, 4).toByteArray())); - } - - @Test(enabled = true, description = "test bytes concat") - public void test08bytesConcat() { - String args = "\"0x1234\",\"p2\",\"0x48e2f56f2c57e3532146eef2587a2a72\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "bytesConcat(bytes,string,bytes16)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(36, trueRes); - } - - @Test(enabled = true, description = "test emit event") - public void test09EmitEvent() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "testEmitEvent()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(6, - ByteArray.toInt(transactionInfo.get().getLog(0).getData().toByteArray())); - } - - - @Test(enabled = true, description = "test bytes convert to byteN overflow") - public void test10Bytes2ByteN() { - String args = "\"0x12345678\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "bytes2BytesN(bytes)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("1234560000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "test bytes convert to byteN underflow") - public void test11Bytes2ByteN() { - String args = "\"0x1234\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "bytes2BytesN(bytes)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("1234000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "get contract address by different function") - public void test12GetConcatAddress() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getContractAddress()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - String res1 = ByteArray.toHexString(transactionExtention.getConstantResult(0) - .substring(0, 32).toByteArray()); - String res2 = ByteArray.toHexString(transactionExtention.getConstantResult(0) - .substring(32, 64).toByteArray()); - Assert.assertEquals(res1, res2); - } - - @Test(enabled = true, description = "test bytes concat with empty string") - public void test13bytesConcatWithEmptyStr() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "bytesConcatWithEmptyStr()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java deleted file mode 100644 index addf73f5112..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java +++ /dev/null @@ -1,306 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; -import static org.tron.protos.Protocol.TransactionInfo.code.SUCESS; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolidity062 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] getSelectorContract = null; - byte[] gasValueContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ExternalSelector.sol"; - String contractName = "TestGasValue"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - gasValueContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 10000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(enabled = true, description = "get selector from contract or interface's external function") - public void test01GetFunctionSelector() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "getContractSelectorNoParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String truerRes = ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("6c4959fa")); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "getContractSelectorWithParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - truerRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("fbb94ff8")); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "getInterfaceSelectorNoParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - truerRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("034899bc")); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: 1}()") - public void test02Call0GasAnd1Value() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,1", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000159", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - byte[] internalReceiver = infoById.get().getInternalTransactions(0) - .getTransferToAddress().toByteArray(); - - long balanceReceiver = PublicMethed.queryAccount(internalReceiver, blockingStubFull) - .getBalance(); - logger.info("transfer to address: " + Base58.encode58Check(internalReceiver) - + "\n balance:" + balanceReceiver); - Assert.assertEquals(1, balanceReceiver); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: 0}()") - public void test03Call0GasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - } - - @Test(enabled = true, description = "inline assembly allow true and false") - public void test04AssembleTrueFalse() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "testAssemblyTrue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, truerRes); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "testAssemblyFalse()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - int falseRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("res: " + falseRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(0, falseRes); - - } - - @Test(enabled = true, description = "test new create2") - public void test05NewCreate2() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "testCreate2()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - byte[] internalReceiver = infoById.get() - .getInternalTransactions(0).getTransferToAddress().toByteArray(); - - long balanceReceiver = PublicMethed.queryAccount(internalReceiver, blockingStubFull) - .getBalance(); - logger.info("transfer to address: " + Base58.encode58Check(internalReceiver) - + "\n balance:" + balanceReceiver); - Assert.assertEquals(1000000, balanceReceiver); - - } - - @Test(enabled = true, description = "test Interface Succeed") - public void test06InterfaceSucceed() { - - String filePath = "src/test/resources/soliditycode/ExternalSelector.sol"; - String contractName = "implementContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] implementContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 10000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(implementContract, - "getSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(66, truerRes); - } - - @Test(enabled = true, description = "call in contract external function like " - + "c.f{gas: 0, value: 1}()") - public void test07CallThis0GasAnd1Value() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "callThisNoGasAnd1Value()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 440000, value: 0}()") - public void test08CallWithGasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "440000,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 1, value: 0}()") - public void test09CallWith1GasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "1,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: > balance}()") - public void test10CallWith0GasAndBigValue() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,9223372036854775800", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 9223372036854775800, value: 0}()") - public void test11CallWithBigGasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "9223372036854775800,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java deleted file mode 100644 index 65515d6db51..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java +++ /dev/null @@ -1,509 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class Opcode { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/opCode.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbiNoOptimize(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - - @Test(enabled = true, description = "test opcode smod, used for int") - public void test01Smod() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "sssmod()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "test opcode extcodecopy return contract bytecode") - public void test02Extcodecopy() { - String base58 = Base58.encode58Check(mapKeyContract); - String txid = PublicMethed.triggerContract(mapKeyContract, - "eextcodecopy(address)", "\"" + base58 + "\"", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()).length() > 0); - - } - - @Test(enabled = true, description = "test opcode coinbase," - + "block.coinbase is sr address which produced the block") - public void test03Coinbase() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "cccoinbase()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertTrue(trueRes.startsWith("00000000000000000000000" - + "0bafb56091591790e00aa05eaddcc7dc1474b5d4b") - || trueRes.startsWith("0000000000000000000000000be88a918d74d0dfd71dc84bd4abf036d0562991")); - - } - - @Test(enabled = true, description = "test opcode difficulty,block.difficulty is always 0") - public void test04Difficulty() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "ddifficulty()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(0, trueRes); - - } - - @Test(enabled = true, description = "test opcode gaslimit,block.gaslimit is always 0") - public void test05Gaslimit() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "gggaslimit()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(0, trueRes); - - } - - @Test(enabled = true, description = "test opcode pc,return current position, " - + "ppppc() can refer to opCode.sol") - public void test06Pc() { - String code = "608060405260838060116000396000f3fe608060405234" - + "8015600f57600080fd5b506004361060285760003560e01c806" - + "36d3a027714602d575b600080fd5b60336045565b6040805191825251" - + "9081900360200190f35b60005890509056fea264697" - + "0667358221220fe03cbd3d2aae7454565f203b9abd76ce74cf0ac" - + "a079b151cf6b8e2bfda2d5c464736f6c634300060c0033"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"name\": \"ppppc\",\n" - + "\t\t\"outputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"internalType\": \"uint256\",\n" - + "\t\t\t\t\"name\": \"a\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"stateMutability\": \"nonpayable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t}\n" - + "]"; - byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(temContract, - "ppppc()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(72, trueRes); - - } - - @Test(enabled = true, description = "test opcode msize,return size of memory, " - + "msize cannot be used if optimize is open, mmmsize() can refer to opCode.sol") - public void test07Msize() { - String code = "608060405260b5806100126000396000f3fe6080604052348015600f5760" - + "0080fd5b506004361060285760003560e01c8063bf1a725d14602d575b600080fd5b60" - + "336047565b604051603e9190605c565b60405180910390f35b600059905090565b6056" - + "816075565b82525050565b6000602082019050606f6000830184604f565b9291505056" - + "5b600081905091905056fea26469706673582212202252652aad4bca9a4aa9db179e03" - + "f7b3bf439f47152e31f45d8587b710bce79664736f6c63430008060033"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"name\": \"mmmsize\",\n" - + "\t\t\"outputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"internalType\": \"uint256\",\n" - + "\t\t\t\t\"name\": \"a\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"stateMutability\": \"nonpayable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t}\n" - + "]"; - byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(temContract, - "mmmsize()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(96, trueRes); - - } - - - @Test(enabled = true, description = "test opcode swap14-16,solidity cannot use optimize") - public void test08Swap() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "ssswap()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, trueRes); - - } - - @Test(enabled = true, description = "test opcode push13-30 but exclude push20 and push29," - + "solidity cannot use optimize") - public void test08Pushx() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "pppushx()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertTrue(trueRes.contains("000000000000000000000000000000000000001" - + "1223344556677889900112233")); - } - - @Test(enabled = true, description = "test opcode callcode,difference with delegatecall " - + "is caller and callvalue,the bytecode is compiled with solidity 0.4.22, " - + "can refer to opCode.sol for code") - public void test09Callcode() { - String code = "60806040526103b4806100136000396000f3006080604052600436106100565763" - + "ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634" - + "cb335db811461005b578063ae02d91d14610081578063ea856db2146100a5575b600080fd5b61007f" - + "73ffffffffffffffffffffffffffffffffffffffff600435166024356100c9565b005b61007f73ffff" - + "ffffffffffffffffffffffffffffffffffff600435166024356101b6565b61007f73ffffffffffffff" - + "ffffffffffffffffffffffffff600435166024356102a3565b604080516024808201849052825180830" - + "39091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffff" - + "ffffffffffff167f66c99139000000000000000000000000000000000000000000000000000000001781529" - + "151815173ffffffffffffffffffffffffffffffffffffffff861693600a93929182919080838360005b8" - + "3811015610170578181015183820152602001610158565b50505050905090810190601f16801561019d5" - + "780820380516001836020036101000a031916815260200191505b5091505060006040518083038185875" - + "af1505050505050565b60408051602480820184905282518083039091018152604490910182526020810" - + "180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f66c99139000000000" - + "000000000000000000000000000000000000000000000001781529151815173fffffffffffffffffffff" - + "fffffffffffffffffff861693600a93929182919080838360005b8381101561025d57818101518382015" - + "2602001610245565b50505050905090810190601f16801561028a5780820380516001836020036101000" - + "a031916815260200191505b5091505060006040518083038185875af2505050505050565b60408051602" - + "480820184905282518083039091018152604490910182526020810180517bfffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffff167f66c991390000000000000000000000000000000000000000" - + "00000000000000001781529151815173ffffffffffffffffffffffffffffffffffffffff8616938291808" - + "38360005b8381101561034457818101518382015260200161032c565b50505050905090810190601f1680" - + "156103715780820380516001836020036101000a031916815260200191505b50915050600060405180830" - + "381855af450505050505600a165627a7a72305820210d132d0c4006264ef113f342556c616d9e69acc20" - + "bfa80cf440a4eac170de80029"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testInCall\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testInCallcode\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testIndelegateCall\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t}\n" - + "]"; - byte[] contractA = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 1000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractA, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - code = "608060405260d2806100126000396000f300608060405260043610603e5763ffffffff7c0" - + "10000000000000000000000000000000000000000000000000000000060003504166366c99" - + "13981146043575b600080fd5b604c600435604e565b005b6040805173fffffffffffffffff" - + "fffffffffffffffffffffff3316815234602082015280820183905290517fac74fdf75f0e5" - + "a43f870f7135801b44f404be82b1dcad73423c542b840d1d64b9181900360600190a150560" - + "0a165627a7a72305820c460a35f70e363777be22b3a4ace5f95533de626073ab4e06d9bf3bbb2cffceb0029"; - abi = "[\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"trans\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"anonymous\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"clog\",\n" - + "\t\t\"type\": \"event\"\n" - + "\t}\n" - + "]"; - byte[] contractC = PublicMethed.deployContract("C", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractC, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String base58C = Base58.encode58Check(contractC); - - String txid = PublicMethed.triggerContract(contractA, - "testInCall(address,uint256)", "\"" + base58C + "\",1", false, - 1, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - String logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - String b = "41" + logRes.substring(24, 64); - String c = logRes.substring(64, 128); - String x = ByteArray.toHexString(contractA); - Assert.assertEquals(b, x); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); - - txid = PublicMethed.triggerContract(contractA, - "testIndelegateCall(address,uint256)", "\"" + base58C + "\",1", false, - 2, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - b = "41" + logRes.substring(24, 64); - c = logRes.substring(64, 128); - x = ByteArray.toHexString(contractExcAddress); - Assert.assertEquals(b, x); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000002", c); - - - txid = PublicMethed.triggerContract(contractA, - "testInCallcode(address,uint256)", "\"" + base58C + "\",1", false, - 3, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - b = "41" + logRes.substring(24, 64); - c = logRes.substring(64, 128); - x = ByteArray.toHexString(contractA); - Assert.assertEquals(b, x); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java deleted file mode 100644 index 14473535bb8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java +++ /dev/null @@ -1,106 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class OverridePrivateFunction { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] gasValueContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - @Test(enabled = false, description = "test override private function") - public void test01OverridePrivateFunction() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/overridePrivateFunction.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - gasValueContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "testOverridePrivate()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(2, truerRes); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java deleted file mode 100644 index 8219070fd5c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java +++ /dev/null @@ -1,455 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class OverrideTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about override(Base1,Base2)") - public void test01OverrideContract515() { - String contractName = "override001"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override001"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override001"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Deploy 0.6.0 about not need override") - public void test02NotNeedOverride() { - String filePath = "./src/test/resources/soliditycode/override002.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about override(Base1,Base2)") - public void test03OverrideMultipleFunctionsWithTheSameName() { - String filePath = "./src/test/resources/soliditycode/override003.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about override modifier") - public void test04OverrideModifier060() { - String filePath = "./src/test/resources/soliditycode/override004.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "7", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1,infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8().contains("x must >= 6")); - - txid = PublicMethed.triggerContract(contractAddress, "setValue2(uint256)", "6", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "8", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(8, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about override modifier") - public void test05OverrideModifier515() { - String contractName = "C"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override002"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override002"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "7", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1,infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8().contains("x must >= 6")); - - txid = PublicMethed.triggerContract(contractAddress, "setValue2(uint256)", "6", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "8", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(8, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 public override external function") - public void test06PublicOverrideExternalFunction060() { - String filePath = "./src/test/resources/soliditycode/override005.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "stopped()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i2()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(-32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "ui()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(23487823, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "origin()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "b32()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "choice()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.5.15 public override external function") - public void test07PublicOverrideExternalFunction515() { - String contractName = "Test"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override003"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override003"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "stopped()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i2()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(-32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "ui()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(23487823, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "origin()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "b32()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "choice()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java deleted file mode 100644 index 65785e99283..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class PayableTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/payable001.sol"; - String contractName = "PayableTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "payable(address) transfer") - public void tryCatchTest001() { - - Account account = PublicMethed - .queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneyTransfer(address,uint256)"; - String argStr = "\"TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - - @Test(enabled = true, description = "payable(address) send") - public void tryCatchTest002() { - - Account account = PublicMethed - .queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneySend(address,uint256)"; - String argStr = "\"TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - - @Test(enabled = true, description = "payable(address(contract)) transfer") - public void tryCatchTest003() { - - String filePath = "src/test/resources/soliditycode/payable001.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] AContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Account account = PublicMethed - .queryAccount(AContract, blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneyTransferWithContract(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(AContract) + "\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(AContract, blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java deleted file mode 100644 index d969f7a707e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class SelectorTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/selector.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - final String aContractAddress = ByteArray.toHexString(contractAddress); - - contractName = "testSelector"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - abi = retMap.get("abI").toString(); - code = retMap.get("byteCode").toString(); - code = PublicMethed.replaceCode(code, aContractAddress.substring(1)); - logger.info("code:" + code); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get the selector of public or external library functions " - + "through member variables") - public void test01GetSelector() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getselector2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - logger.info("result: " + ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("f8b2cb4f", PublicMethed.removeAll0sAtTheEndOfHexStr(ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray()).substring(0, 64))); - Assert.assertEquals("b4cef28d", PublicMethed.removeAll0sAtTheEndOfHexStr(ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray()).substring(64))); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java deleted file mode 100644 index b38ec456fca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class SlotAndOffsetNewGrammer { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - /** - * trigger contract and assert. - */ - public void assertResult(byte[] contractAddress) { - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, "getA()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - String res = "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000000"; - System.out.println(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(res, - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - txid = PublicMethed.triggerContract(contractAddress, "getE()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - res = "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000000"; - System.out.println(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(res, - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Deploy 0.6.x new grammer") - public void testSlotAndOffsetOldVersion() { - String contractName = "A"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_slotAndOffset_06x"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_slotAndOffset_06x"); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - assertResult(contractAddress); - - } - - @Test(enabled = true, description = "Deploy 0.7.0 new grammer") - public void testSlotAndOffsetNew() { - String filePath = "./src/test/resources/soliditycode/slotAndOffsetNewGrammer.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - assertResult(contractAddress); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java deleted file mode 100644 index 765fa4c3c99..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StringSplitTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/stringSplit.sol"; - String contractName = "testStringSplit"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get s1 n1") - public void test01GetS1N1() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS1()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s12,./", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS1N1()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s12,./", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s2 n2") - public void test01GetS2N2() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s123?\\'.", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS2N2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s123?\'.", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s3 n3") - public void test01GetS3N3() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS3()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS3N3()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s4 n4") - public void test01GetS4N4() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS4()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS4N4()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java deleted file mode 100644 index 9d450b0392f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java +++ /dev/null @@ -1,334 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TvmVote { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - int freezeCount = 100000000; - int voteCount = 1; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/tvmVote.sol"; - String contractName = "TestVote"; - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "query reward balance") - public void test01QueryRewardBalance() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryRewardBalance()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - long trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + trueRes); - Assert.assertEquals(0, trueRes); - - GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder().setValue(ByteString - .copyFrom(mapKeyContract)) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - org.testng.Assert.assertEquals(trueRes, reward); - } - - - @Test(enabled = true, description = "freeze balance and vote witness") - public void test02VoteWitness() { - String methodStr = "freeze(address,uint256,uint256)"; - String receiverAdd = Base58.encode58Check(mapKeyContract); - String args = "\"" + receiverAdd + "\"," + freezeCount + ",1"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, - methodStr, args, false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("freezeForEnergy", note); - Assert.assertEquals(freezeCount, internal.getCallValueInfo(0).getCallValue()); - - String witness58Add = Base58.encode58Check(witnessAddress); - args = "[\"" + witness58Add + "\"],[" + voteCount + "]"; - logger.info("vote args: " + args); - methodStr = "voteWitness(address[],uint256[])"; - triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - internal = transactionInfo.get().getInternalTransactions(0); - note = internal.getNote().toStringUtf8(); - Assert.assertEquals("voteWitness", note); - Assert.assertTrue(internal.getExtra().length() > 1); - - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - int voteCount = info.getVotesCount(); - logger.info("voteCount: " + voteCount); - Assert.assertEquals(1, voteCount); - } - - @Test(enabled = true, description = "query contract address is Sr Candidate or not") - public void test03IsSrCandidate() { - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, 0); - } - - @Test(enabled = true, description = "query sr address is Sr Candidate or not") - public void test04IsSrCandidate() { - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(1, 1); - } - - @Test(enabled = true, description = "query zero address is Sr Candidate or not") - public void test05IsSrCandidate() { - String args = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, 0); - } - - @Test(enabled = true, description = "query sr's total vote count") - public void test06querySrTotalVoteCount() { - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryTotalVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, trueRes); - } - - @Test(enabled = true, description = "query contract's total vote count") - public void test07queryContractTotalVoteCount() { - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryTotalVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(freezeCount / 1000000, trueRes); - } - - @Test(enabled = true, description = "query vote count") - public void test08queryVoteCount() { - String from = Base58.encode58Check(mapKeyContract); - String to = Base58.encode58Check(witnessAddress); - String args = "\"" + from + "\",\"" + to + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryVoteCount(address,address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(voteCount, trueRes); - } - - @Test(enabled = true, description = "query contract used vote count") - public void test09queryUsedVoteCount() { - String from = Base58.encode58Check(mapKeyContract); - String args = "\"" + from + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryUsedVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(voteCount, trueRes); - } - - @Test(enabled = true, description = "query witnesses received vote count") - public void test10queryReceivedVoteCount() { - String witness = Base58.encode58Check(witnessAddress); - String args = "\"" + witness + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryReceivedVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertTrue(trueRes > 0); - Optional list = PublicMethed.listWitnesses(blockingStubFull); - long receiveCount = 0; - String temAdd; - for (int i = 0; i < list.get().getWitnessesCount(); i++) { - temAdd = Base58.encode58Check(list.get().getWitnesses(i).getAddress().toByteArray()); - if (witness.equals(temAdd)) { - receiveCount = list.get().getWitnesses(i).getVoteCount(); - break; - } - } - Assert.assertEquals(trueRes, receiveCount); - } - - @Test(enabled = true, description = "withdraw reward") - public void test11WithdrawReward() { - String methodStr = "withdrawReward()"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("withdrawReward", note); - Assert.assertEquals(1, internal.getCallValueInfoCount()); - Assert.assertEquals("", internal.getCallValueInfo(0).toString()); - } - - @Test(enabled = true, description = "unfreeze energy") - public void test12Unfreeze() { - String methodStr = "unfreeze(address,uint256)"; - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\",1"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("unfreezeForEnergy", note); - Assert.assertEquals(freezeCount, internal.getCallValueInfo(0).getCallValue()); - } - - @Test(enabled = true, description = "kill me") - public void test13Suicide() { - String methodStr = "killme(address)"; - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed - .getContract(mapKeyContract, blockingStubFull); - Assert.assertEquals("", smartContract.getAbi().toString()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java deleted file mode 100644 index c23787ffc5a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VirtualTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about virtual") - public void test01OverrideContract515() { - String contractName = "Z"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_virtual001"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_virtual001"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setString(string)", "\"1q2w\"", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "z()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "3171327700000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about virtual") - public void test02OverrideContract060() { - String filePath = "./src/test/resources/soliditycode/virtual001.sol"; - String contractName = "Z"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setString(string)", "\"1q2w\"", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "z()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "3171327700000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java deleted file mode 100644 index c462d208263..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class assemblyTest { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/assemblyTest.sol"; - String contractName = "assemblyTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get assembly references fuction number, type: uint") - public void test01AssemblyReferencesUint() { - String methodStr = "getZuint()"; - String argStr = ""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit,"0",0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals(1,ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - methodStr = "getZuint2()"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - int ContractResult = ByteArray.toInt(infoById.get() - .getContractResult(0).toByteArray()); - Assert.assertEquals(1,ContractResult); - - - } - - @Test(enabled = true, description = "get assembly references fuction number, type: boolen") - public void test02AssemblyReferencesBoolen() { - String methodStr = "getZbool()"; - String argStr = ""; - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit,"0",0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals(1,ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - methodStr = "getZbool2()"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - int ContractResult = ByteArray.toInt(infoById.get() - .getContractResult(0).toByteArray()); - Assert.assertEquals(1,ContractResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java deleted file mode 100644 index d11e2338ddc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class calldataTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/calldata.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java deleted file mode 100644 index 093e4a38324..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class constructorDefaultsTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(dev001Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Constructor default test") - public void Test01ConstructorDefault() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 200000000L, fromAddress, testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - String filePath = "./src/test/resources/soliditycode/ConstructorDefaults.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(bool)"; - String data = "0"; - String txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] contractaddress = null; - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(info.toString()); - Assert.assertTrue(info.get().getResultValue() == 0); - data = "false"; - txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(info.toString()); - Assert.assertTrue(info.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java deleted file mode 100644 index 4230379af5a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class enumAndStructTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - String filePath = "src/test/resources/soliditycode/enumAndStruct.sol"; - String contractName = "enumAndStructTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get Enum and Struct") - public void EnumAndStructTest001() { - - - String methodStr = "getvalue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testFoundationAddress, testFoundationKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(1, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java deleted file mode 100644 index bfa8ebf1561..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java +++ /dev/null @@ -1,156 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class fallbackOldVersion { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressCall = null; - byte[] contractAddressTest0 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_fallbackOldVersionTest"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_fallbackOldVersionTest"); - String contractName = "Test0"; - contractAddressTest0 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_fallbackOldversionCall"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_fallbackOldVersionCall"); - contractName = "Call"; - contractAddressCall = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "test fallback") - public void test01FallbakTest() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String txid = ""; - String method = "call(address)"; - long value = 10000; - String para = "\"" + Base58.encode58Check(contractAddressTest0) + "\""; - txid = PublicMethed.triggerContract(contractAddressCall, method, para, false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - - txid = PublicMethed.triggerContract(contractAddressCall, method, para, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - //@AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddressCall, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest0, contractExcKey, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java deleted file mode 100644 index 63bd60a0d1c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java +++ /dev/null @@ -1,376 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class fallbackReceive { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressCaller = null; - byte[] contractAddressTest0 = null; - byte[] contractAddressTest1 = null; - byte[] contractAddressTest2 = null; - byte[] contractAddressTestPayable = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/fallbackUpgrade.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddressCaller = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, - null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test0"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest0 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test1"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest1 = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test2"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest2 = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "TestPayable"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTestPayable = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "contract test0 has no fallback method") - public void test001NoFallback() { - String txid = ""; - String method = "hello()"; - txid = PublicMethed.triggerContract(contractAddressTest0, - method, "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - } - - @Test(enabled = true, description = "contract test0 has no fallback method") - public void test002NoFallback() { - String txid = ""; - String method = "callTest0(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest0) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test011Fallback() { - String txid = ""; - String method = "callTest1(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest1) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - List logList = infoById.get().getLogList(); - if (!Objects.isNull(logList)) { - for (Protocol.TransactionInfo.Log log : logList) { - //logger.info("LOG data info:" + tmp); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(log.getData().toByteArray())); - } - } - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test012Fallback() { - String txid = ""; - String method = "callTest2(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest1) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("REVERT", infoById.get().getReceipt().getResult().toString()); - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test013Fallback() { - String txid = ""; - txid = PublicMethed.triggerContract(contractAddressTest1, - "hello()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - txid = PublicMethed.triggerContract(contractAddressTest1, - "hello2()", "#", false, - 100000, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("REVERT", infoById.get().getReceipt().getResult().toString()); - } - - @Test(enabled = true, description = "contract test02 has fallback payable method") - public void test021FallbackPayable() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String txid = ""; - long value = 10000; - txid = PublicMethed.triggerContract(contractAddressTest2, "hello()", "#", false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - - String method = "callTest2(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest2) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, method, para, false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("callTest2 result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - fee = infoById.get().getFee(); - logger.info("callTest2 fee:" + fee); - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance2 = infoafter.getBalance(); - logger.info("callTest2 afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance2 + fee + value == afterBalance); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test041FallbackReceive() { - String txid = ""; - String method = "callTestPayable1(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTestPayable) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - Assert.assertEquals("receive", - PublicMethed.getContractStringMsg(infoById.get().getLog(1).getData().toByteArray())); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test042FallbackReceive() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - String txid = ""; - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String method = "callTest2(address)"; - long value = 10000; - String para = "\"" + Base58.encode58Check(contractAddressTestPayable) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - value, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test05FallbackReceive() { - String txid = ""; - long value = 10000; - txid = PublicMethed.triggerContract(contractAddressTestPayable, - "method()", "#", false, - value, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - Protocol.Account infoafter = PublicMethed - .queryAccount(contractAddressTestPayable, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractAddressTestPayable, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - logger.info("contract balance:" + afterBalance.longValue()); - Assert.assertEquals(11000, afterBalance.longValue()); - - txid = PublicMethed.triggerContract(contractAddressTestPayable, - "#", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.get().getResult().toString()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("receive", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - } - - //@AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddressTest0, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest1, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest2, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTestPayable, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressCaller, contractExcKey, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java deleted file mode 100644 index c1bb682a801..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class mappingGetterTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/mappingGetter.sol"; - String contractName = "mappingGetter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java deleted file mode 100644 index 82ff090f2e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java +++ /dev/null @@ -1,140 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class stateVariableShadowing { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/stateVariableShadowing.sol"; - String contractName = "stateVariableShadowing"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Verify that the compilation is successful") - public void test01VerifyCompile() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - ArrayList methods = new ArrayList(); - methods.add("setValue2(uint256)"); - methods.add("setValue3(uint256)"); - for (String tmp : methods) { - System.out.println(tmp); - txid = PublicMethed.triggerContract(contractAddress, - tmp, "100", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - } - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java deleted file mode 100644 index 57aca964fad..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class typeNameTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/typeName.sol"; - String contractName = "TypeName"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - - @Test(enabled = true, description = "Trigger testTypeName function") - public void test02TriggerTestTypeNameFunction() { - final String txid = PublicMethed.triggerContract(contractAddress, - "testTypeName()", "#", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("infoById:" + infoById.get()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8() - .contains("TypeName")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java deleted file mode 100644 index 11ebe1e45ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java +++ /dev/null @@ -1,253 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "Trigger old ShiftLeft ShiftRight") - public void test1OldInstruction() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmOldCommand001.sol"; - String contractName = "binaryRightContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed.triggerContract(contractAddress, - "binaryMoveR(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed.triggerContract(contractAddress, - "binaryLiftR(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - - } - - @Test(enabled = true, description = "Trigger new ShiftLeft ShiftRight ShiftRightSigned") - public void test2NewInstruction() { - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(10, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(2, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java deleted file mode 100644 index 03e15dce8ce..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java +++ /dev/null @@ -1,265 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "OLd compiler compile shift instruction") - public void test1Oldcompile() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "TestBitwiseShift"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5" - + "7600080fd5b506101478061003a6000396000f3006080604052600436106100565763ffffffff7c0100" - + "000000000000000000000000000000000000000000000000000000600035041663614eb4da811461005" - + "b578063b5675d6d146100a2578063baf27c0c146100d7575b600080fd5b34801561006757600080fd5b" - + "50d3801561007457600080fd5b50d2801561008157600080fd5b5061009060043560243561010c565b6" - + "0408051918252519081900360200190f35b3480156100ae57600080fd5b50d380156100bb57600080fd" - + "5b50d280156100c857600080fd5b50610090600435602435610111565b3480156100e357600080fd5b5" - + "0d380156100f057600080fd5b50d280156100fd57600080fd5b50610090600435602435610116565b90" - + "1b90565b901d90565b901c905600a165627a7a723058200d5cc53ffdc6db62c4d7414d8b7d95c98218e" - + "50b4c1ea5961d527de1439733450029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"num\",\"type\":\"uint256\"}," - + "{\"name\":\"input\",\"type\":\"uint256\"}],\"name\":\"shlTest\",\"outputs\":" - + "[{\"name\":\"out\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":" - + "\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":" - + "\"num\",\"type\":\"uint256\"},{\"name\":\"input\",\"type\":\"uint256\"}],\"name" - + "\":\"sarTest\",\"outputs\":[{\"name\":\"out\",\"type\":\"bytes32\"}],\"payable" - + "\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant" - + "\":false,\"inputs\":[{\"name\":\"num\",\"type\":\"uint256\"},{\"name\":\"input\"" - + ",\"type\":\"uint256\"}],\"name\":\"shrTest\",\"outputs\":[{\"name\":\"out\",\"" - + "type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"" - + "type\":\"function\"}]"; - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed - .triggerContract(contractAddress, "sarTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed - .triggerContract(contractAddress, "shlTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - txid = PublicMethed - .triggerContract(contractAddress, "shrTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "New compiler compile shift instruction") - public void test2Newcompile() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed - .triggerContract(contractAddress, "sarTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed - .triggerContract(contractAddress, "shlTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - txid = PublicMethed - .triggerContract(contractAddress, "shrTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java deleted file mode 100644 index 66da905e03e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java +++ /dev/null @@ -1,332 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft with displacement number too short ") - public void test1ShiftLeft() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight with displacement number too short ") - public void test2ShiftRight() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("00007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned " - + "with displacement number too short ") - public void test3ShiftRightSigned() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("00007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java deleted file mode 100644 index b382ae75a56..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java +++ /dev/null @@ -1,1040 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftLeft() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000002")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0xff") - public void test3ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x0100") - public void test4ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x0101") - public void test5ShiftLeft() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test6ShiftLeft() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test7ShiftLeft() { - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test8ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void test9ShiftLeft() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftLeft10() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void testShiftLeft11() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftLeft12() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java deleted file mode 100644 index 8030a54490f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java +++ /dev/null @@ -1,1049 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftRight() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void test3ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - String originNumber = String.valueOf(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000"))); - String valueNumber = String.valueOf(ByteArray.toLong((ByteArray - .fromHexString("0x01")))); - String num = valueNumber + "," + originNumber; - - logger.info("returnnumber:" + originNumber); - logger.info("returnnumber1:" + valueNumber); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x4000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xff") - public void test4ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0100") - public void test5ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0101") - public void test6ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test7ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test8ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test9ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRight10() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftRight11() { - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRight12() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java deleted file mode 100644 index 1991fc5a52f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java +++ /dev/null @@ -1,1539 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftRightSigned() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void test3ShiftRightSigned() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xc000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xff") - public void test4ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0100") - public void test5ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0101") - public void test6ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test7ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x00")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test8ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test9ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRightSigned10() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x0100")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftRightSigned11() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x4000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xfe") - public void testShiftRightSigned12() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x4000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xfe")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xf8") - public void testShiftRightSigned13() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xf8")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x000000000000000000000000000000000000000000000000000000000000007f")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xfe") - public void testShiftRightSigned14() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xfe")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void testShiftRightSigned15() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRightSigned16() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRightSigned17() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x0101")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRightSigned18() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java deleted file mode 100644 index a0b1f62289f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java +++ /dev/null @@ -1,624 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import static org.hamcrest.core.StringContains.containsString; -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTestSendCoin001 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Sendcoin and transferAsset to contractAddresss ," - + "then selfdestruct") - public void testSendCoinAndTransferAssetContract001() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "src/test/resources/soliditycode/contractTrcToken031.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 5; - - final String deployContractTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployContractTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (deployContractTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Return ret = PublicMethed - .transferAssetForReturn(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - Return ret1 = PublicMethed - .sendcoinForReturn(transferTokenContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer TRX to a smartContract.", - ret1.getMessage().toStringUtf8()); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - String txid = PublicMethed - .triggerContract(transferTokenContractAddress, "kill(address)", num, false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long contractAssetCountBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - long contractBefore = PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull) - .getBalance(); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Assert.assertTrue(PublicMethed - .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(transferTokenContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAssetCountAfter = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - long contractAfetr = PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(contractAssetCountBefore + 100L == contractAssetCountAfter); - Assert.assertTrue(contractBefore + 1_000_000L == contractAfetr); - - } - - - @Test(enabled = true, description = "Use create to generate a contract address " - + "Sendcoin and transferAsset to contractAddresss ,then selfdestruct,") - public void testSendCoinAndTransferAssetContract002() { - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "src/test/resources/soliditycode/contractTransferToken001.sol"; - - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 5; - - final String deployContractTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployContractTxid, blockingStubFull); - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - String txid = PublicMethed - .triggerContract(transferTokenContractAddress, "newB()", "#", false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("create Address : " + addressFinal); - byte[] testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - Return ret = PublicMethed - .transferAssetForReturn(testContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - Long contractAssetCount = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(0L), contractAssetCount); - - Return ret1 = PublicMethed - .sendcoinForReturn(testContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer TRX to a smartContract.", - ret1.getMessage().toStringUtf8()); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - txid = PublicMethed - .triggerContract(testContractAddress, "kill(address)", num, false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long contractAssetCountBefore = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - long contractBefore = PublicMethed.queryAccount(testContractAddress, blockingStubFull) - .getBalance(); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Assert.assertTrue(PublicMethed - .transferAsset(testContractAddress, assetAccountId.toByteArray(), 100L, dev001Address, - dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(testContractAddress, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAssetCountAfter = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - long contractAfetr = PublicMethed.queryAccount(testContractAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(contractAssetCountBefore + 100L == contractAssetCountAfter); - Assert.assertTrue(contractBefore + 1_000_000L == contractAfetr); - } - - - @Test(enabled = true, description = "Use create2 to generate a contract address " - + "Sendcoin and transferAsset to contractAddresss ,then selfdestruct") - public void testSendCoinAndTransferAssetContract003() { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String sendcoin = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, fromAddress, testKey002, - blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - String filePath = "src/test/resources/soliditycode/create2contractn2.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - - Return ret = PublicMethed - .transferAssetForReturn(returnAddressBytes, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - - Return ret1 = PublicMethed - .transferAssetForReturn(returnAddressBytes, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret1.getMessage().toStringUtf8()); - - txid = PublicMethed - .triggerContract(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - txid = PublicMethed - .triggerContract(returnAddressBytes, "set()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed - .triggerContract(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(5 == returnnumber); - - String param1 = "\"" + Base58.encode58Check(returnAddressBytes) + "\""; - - txid = PublicMethed - .triggerContract(returnAddressBytes, "testSuicideNonexistentTarget(address)", param1, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals("suicide", - ByteArray.toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray())); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : No contract or not a valid smart contract")); - - Assert.assertTrue(PublicMethed - .transferAsset(returnAddressBytes, assetAccountId.toByteArray(), 100L, dev001Address, - dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(returnAddressBytes, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] returnAddressBytes1 = infoById3.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress1 = Base58.encode58Check(returnAddressBytes1); - Assert.assertEquals(returnAddress1, returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes1, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - ret = PublicMethed - .transferAssetForReturn(returnAddressBytes1, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - - ret1 = PublicMethed - .transferAssetForReturn(returnAddressBytes1, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret1.getMessage().toStringUtf8()); - - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java deleted file mode 100644 index 518e49aad24..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestResourceReceiver { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = false, description = "Suicide existent Target") - public void test1SuicideExistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(testNetAccountAddress, - 1000000, 0, 1, - ByteString.copyFrom(contractAddress), testNetAccountKey, blockingStubFull)); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] existentAddress = ecKey2.getAddress(); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Account contractafter = PublicMethed.queryAccount(contractAddress, blockingStubFull1); - long contractBalance = contractafter.getBalance(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(contractBalance, 0); - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertNull(txid); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - PublicMethed.unFreezeBalance(testNetAccountAddress, testNetAccountKey, 1, - contractAddress, blockingStubFull); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java deleted file mode 100644 index cd62ed8edb6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java +++ /dev/null @@ -1,920 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Transfer trx insufficient balance") - public void test001TransferTrxInsufficientBalance() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 2000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "2000001"; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer balance enough") - public void test002TransferEnough() { - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - logger.info("infoById" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee - 1 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - - @Test(enabled = true, description = "Transfer trx nonexistent target") - public void test003TransferTrxNonexistentTarget() { - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(2, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertEquals(energyUsageTotal2 + EnergyCost.getNewAcctCall(), - energyUsageTotal); - - } - - - @Test(enabled = true, description = "Transfer trx to myself") - public void test004TransferTrxSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxSelf(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer trx nonexistent target and insufficient balance") - public void test005TransferTrxNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "10000000" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer trx to myself and insufficient balance") - public void test006TransferTrxSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String txid = ""; - String num = "1000000000"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxSelf(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "PreCompiled transfertoken with value," - + " long.max < value or long.min > value") - public void test007TransferTrckenPreCompiled() { - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - String num = "1"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledLongMax1()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledLongMin1()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - } - - @Test(enabled = false, description = "PreCompiled tokenbalance") - public void test008TransferTrctoken() { - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ByteString assetAccountId = null; - final long TotalSupply = 10000000L; - long now = System.currentTimeMillis(); - String tokenName = "testAssetIssue_" + Long.toString(now); - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.transferAsset(contractAddress, - assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - blockingStubFull)); - - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("returnAddressBytesAccountCountBefore : " + returnAddressBytesAccountCountBefore); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = - "\"" + Base58.encode58Check(contractAddress) + "\"," + "\"" + assetAccountId.toStringUtf8() - + "\""; - //String num = "\""+Base58.encode58Check(contractAddress) +"\","+ "\"" + -1 + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenTest(address,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - - } - - @Test(enabled = true, description = "PreCompiled address(0x1) query tokenbalance") - public void test009TransferTrctoken() { - //address: 410000000000000000000000000000000000000001 - String addressx = "T9yD14Nj9j7xAB4dbGeiX9h8unkKLxmGkn"; - byte[] addressxx = WalletClient.decodeFromBase58Check(addressx); - - Assert.assertTrue(PublicMethed - .sendcoin(addressxx, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ByteString assetAccountId = null; - final long TotalSupply = 10000000L; - long now = System.currentTimeMillis(); - String tokenName = "testAssetIssue_" + Long.toString(now); - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed.transferAsset(addressxx, - assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(addressxx, assetAccountId, blockingStubFull); - logger.info("returnAddressBytesAccountCountBefore : " + returnAddressBytesAccountCountBefore); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - //String num = "\""+Base58.encode58Check(contractAddress) - // +"\","+ "\"" + assetAccountId.toStringUtf8() + "\""; - String num = "\"" + assetAccountId.toStringUtf8() + "\""; - //String num = "\""+Base58.encode58Check(contractAddress) +"\","+ "\"" + -1 + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledTokenId(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "transferTrx to nonexistent target ,but revert") - public void test010TransferRevert() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxrevert(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java deleted file mode 100644 index f3691a62b15..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java +++ /dev/null @@ -1,582 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Send balance not enough") - public void test1SendNotEnough() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 3000000L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "3000001"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxInsufficientBalance(uint256)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "Send balance enough") - public void test2SendEnough() { - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxInsufficientBalance(uint256)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee - 1 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - - @Test(enabled = true, description = "Send trx nonexistent target") - public void test3SendTrxNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1, nonexistentAddressAccount.getBalance()); - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertNotEquals(energyUsageTotal2, - energyUsageTotal + EnergyCost.getNewAcctCall()); - - nonexistentAddressAccount = PublicMethed.queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(2, nonexistentAddressAccount.getBalance()); - - } - - - @Test(enabled = true, description = "Send trx self") - public void test4SendTrxSelf() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxSelf(uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Send trx nonexistent target and balance not enough") - public void test5SendTrxNonexistentTarget() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - - String num = "100000000" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - - @Test(enabled = true, description = "Send trx self and balance not enough") - public void test6SendTrxSelf() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String txid = ""; - - String num = "1000000000"; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxSelf(uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "Send trx nonexistent target, but revert") - public void test7SendTrxNonexistentTargetRevert() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxRevert(uint256,address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java deleted file mode 100644 index 5aa9255e54a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java +++ /dev/null @@ -1,817 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed003 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "TransferToken enough tokenBalance") - public void test1TransferTokenEnough() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 100L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Assert.assertTrue(PublicMethed.transferAsset(contractAddress, - // assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(testNetAccountCountBefore + 1 == testNetAccountCountAfter); - Assert.assertTrue(contractAccountCountBefore - 1 == contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "TransferToken insufficient tokenBalance") - public void test2TransferTokenNotEnough() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1000" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - logger.info("infoById:" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - - @Test(enabled = true, description = "TransferToken to nonexistent target") - public void test3TransferTokenNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"1" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.longValue()); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 2, contractAccountCountAfter.longValue()); - - Assert.assertEquals(energyUsageTotal, - energyUsageTotal2 + EnergyCost.getNewAcctCall()); - - nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(2L, nonexistentAddressAccount.longValue()); - } - - - @Test(enabled = true, description = "TransferToken to myself") - public void test4TransferTokenSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenSelf(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "transfer trc10 failed: Cannot transfer asset to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "TransferToken notexist tokenID ") - public void test5TransferTokenNotexist() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String fakeassetAccountId = Long.toString(0L); - - String num = "1" + ",\"" + fakeassetAccountId + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - - @Test(enabled = true, description = "TransferToken to nonexistent target and " - + "insufficient tokenBalance") - public void test7TransferTokenNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"100000000000" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" - + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertEquals(afterBalance + fee, beforeBalance.longValue()); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccount.longValue()); - - - } - - - @Test(enabled = true, description = "TransferToken to myself and insufficient tokenBalance") - public void test8TransferTokenSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1000000000000000" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenSelf(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - @Test(enabled = true, description = "TransferToken to nonexistent target, but revert") - public void test9TransferTokenNonexistentTargetRevert() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"1" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenRevert(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccount.longValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java deleted file mode 100644 index 9c9fea1af32..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java +++ /dev/null @@ -1,576 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static ByteString assetAccountId2 = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress3 = ecKey3.getAddress(); - String contractExcKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - long energyUsageTotal = 0; - long energyUsageTotal2 = 0; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - } - - @Test(enabled = true, description = "Suicide nonexistent target") - public void test1SuicideNonexistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContractFallbackReceive(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100,1000L, assetAccountId.toStringUtf8(), 1000L, - null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - Assert.assertNotEquals(10000000, energyUsageTotal); - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - Assert.assertEquals(0, assetIssueId.length()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1000000L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1000L, nonexistentAddressAccountTokenBalance.longValue()); - } - - @Test(enabled = true, description = "Suicide existent target") - public void test2SuicideExistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress2 = PublicMethed.deployContractFallbackReceive(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100,1000L, assetAccountId.toStringUtf8(), - 1000L,null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - Assert.assertTrue(PublicMethed - .sendcoin(nonexistentAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Account contractafter = PublicMethed.queryAccount(contractAddress2, blockingStubFull1); - long contractBalance = contractafter.getBalance(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(contractBalance, 0); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - Assert.assertEquals(energyUsageTotal, energyUsageTotal2); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(3000000L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(2000L, nonexistentAddressAccountTokenBalance.longValue()); - - } - - @Test(enabled = true, description = "Suicide nonexistent target, but revert") - public void test3SuicideNonexistentTargetRevert() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress3 = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Assert.assertTrue(PublicMethed - //.sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress1 = ecKey2.getAddress(); - - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress1) + "\""; - - txid = PublicMethed.triggerContract(contractAddress3, - "testSuicideRevert(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal < 1000000000L); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress1, blockingStubFull1); - Assert.assertEquals(1000000L, nonexistentAddressAccount.getBalance()); - } - - @Test(enabled = true, description = "transfer to a suicide contract address same token") - public void test4transferToSuicideContractSameToken() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final byte[] contractAddress4 = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L,null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(contractAddress, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.getBalance()); - - num = - "\"1" + "\",\"" + Base58.encode58Check(contractAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountAfter.longValue()); - } - - @Test(enabled = true, description = "transfer to a suicide contract address different token") - public void test5transferToSuicideContractDifferentToken() { - // create different token - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress3, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey3, blockingStubFull)); - assetAccountId2 = PublicMethed.queryAccount(contractExcAddress3, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final byte[] contractAddress4 = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, 1000000000L, - assetAccountId2.toStringUtf8(), 1000L,null, contractExcKey3, - contractExcAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress3, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey3, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(contractAddress, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.getBalance()); - - String num = - "\"1" + "\",\"" + Base58.encode58Check(contractAddress) + "\",\"" + assetAccountId2 - .toStringUtf8() + "\""; - String txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress3, contractExcKey3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Long contractAccountCountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountTokenBalance.longValue()); - Long contractAccountCountTokenBalance2 = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountTokenBalance2.longValue()); - - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - Assert.assertEquals(0, assetIssueId.length()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java deleted file mode 100644 index 5971122a9c8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java +++ /dev/null @@ -1,493 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - - filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - contractAddress1 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - } - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - - filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - contractAddress1 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - logger.info("caller address : " + Base58.encode58Check(contractAddress1)); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = true, description = "TransferFailed for function call_value ") - public void triggerContract01() { - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - long paramValue = 1; - - // transfer trx to self`s account - String param = "\"" + paramValue + "\",\"" + Base58.encode58Check(contractAddress) + "\""; - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - Assert.assertEquals("TRANSFER_FAILED", infoById.get().getReceipt().getResult().toString()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - infoById.get().getResMessage().toStringUtf8()); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to unactivate account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress2 = ecKey2.getAddress(); - param = "\"" + paramValue + "\",\"" + Base58.encode58Check(accountExcAddress2) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - Assert.assertEquals(99L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to caller, value enough , function success contractResult(call_value) successed - param = "\"" + paramValue + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(1, contractResult); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(98L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to caller, value not enough, function success - // but contractResult(call_value) failed - param = "\"" + 100 + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - //contractResult`s first boolean value - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(0, contractResult); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(98L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - @Test(enabled = true, description = "TransferFailed for create") - public void triggerContract02() { - final Long contractBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - long paramValue = 1; - String param = "\"" + paramValue + "\""; - - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCreateTrxInsufficientBalance(uint256)", param, false, - 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertEquals(contractBalance - 1, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - param = "\"" + (contractBalance + 1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCreateTrxInsufficientBalance(uint256)", param, false, - 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResMessage().toStringUtf8(), "REVERT opcode executed"); - Assert.assertEquals(contractBalance - 1, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - @Test(enabled = true, description = "TransferFailed for create2") - public void triggerContract03() { - final Long contractBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 15L, accountExcAddress, accountExcKey, blockingStubFull)); - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - - String filePath = "./src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", param, false, 0L, maxFeeLimit, - accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Long afterBalance = 0L; - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info("contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(contractBalance - 10L, afterBalance.longValue()); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed - .triggerContract(contractAddress, "deploy2(bytes,uint256)", param, false, 0L, maxFeeLimit, - accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info("contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - Assert.assertEquals(contractBalance - 10L, afterBalance.longValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - } - - @Test(enabled = true, description = "Triggerconstant a transfer function") - public void triggerContract04() { - Account account = PublicMethed.queryAccount(accountExcAddress, blockingStubFull); - Account contractAccount = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - final Long AccountBeforeBalance = account.getBalance(); - final Long contractAccountBalance = contractAccount.getBalance(); - - TransactionExtention return1 = PublicMethed.triggerConstantContractForExtention(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", "1", false, 0L, 1000000000, "0", 0L, - accountExcAddress, accountExcKey, blockingStubFull); - Assert.assertEquals(response_code.SUCCESS, return1.getResult().getCode()); - /*Assert.assertEquals( - "class org.tron.core.vm.program.Program$StaticCallModificationException " - + ": Attempt to call a state modifying opcode inside STATICCALL", - return1.getResult().getMessage().toStringUtf8());*/ - - logger.info("return1: " + return1); - - account = PublicMethed.queryAccount(accountExcAddress, blockingStubFull); - contractAccount = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(AccountBeforeBalance.longValue(), account.getBalance()); - Assert.assertEquals(contractAccountBalance.longValue(), contractAccount.getBalance()); - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java deleted file mode 100644 index c75f2b312af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed006.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - - filePath = "src/test/resources/soliditycode/TransferFailed006.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - logger.info("caller address : " + Base58.encode58Check(contractAddress1)); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = false, description = "TransferFailed for create") - public void triggerContract() { - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - long paramValue = 1000000; - String param = "\"" + paramValue + "\""; - - String triggerTxid = PublicMethed.triggerContract(contractAddress, - "testCreateTrxInsufficientBalance(uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed.triggerContract(contractAddress, - "testCreateTrxInsufficientBalance(uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResMessage().toStringUtf8(), "REVERT opcode executed"); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java deleted file mode 100644 index 886bc8683ee..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java +++ /dev/null @@ -1,201 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = false, description = "TransferFailed for create2") - public void triggerContract() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 15L, accountExcAddress, accountExcKey, blockingStubFull)); - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - - String filePath = "./src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed.triggerContract(contractAddress, - "deploy(bytes,uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - long afterBalance = 0L; - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - logger.info( - "contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(5L, afterBalance); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed.triggerContract(contractAddress, - "deploy(bytes,uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info( - "contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(5L, afterBalance); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java deleted file mode 100644 index 1d118bedd8b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java +++ /dev/null @@ -1,485 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed008 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static ByteString assetAccountId2 = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] contractAddress = null; - byte[] contractAddress2 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress3 = ecKey3.getAddress(); - String contractExcKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - System.out.println("assetAccountId:" + assetAccountId.toStringUtf8()); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - } - - - @Test(enabled = false, description = "TransferToken to old contractAddress") - public void test1TransferToOldContractAddress() { - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAccountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1000L, contractAccountTokenBalance.longValue()); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - // TUtbvvfggwQLrDZCNqYpfieCvCaKgKk5k9 selfdestruct contractAddress - // TQ1sSomxqmgqKiGqL3Lt8iybHt28FvUTwN exist accountAddress have token - // TWvKUjxH37F9BoeBrdD1hhWf7Es4CDTsRP exist contractAddress haven't token - // TKK8PhmACsJVX9T7Jkwr2QuWmhB8LjvwUW exist accountAddress haven't token - // v4.1.2 contract address ----Manual input - String oldContractAddress = "TV1ExzvFmSTMj67sxnzHrkZmjpsG5QWSne"; - String num = - "\"" + oldContractAddress + "\",\"1\",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "transferTokenTest(address,uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long oldContractAddressAccount = PublicMethed.getAssetIssueValue( - PublicMethed.decode58Check(oldContractAddress), assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, oldContractAddressAccount.longValue()); - } - - @Test(enabled = true, description = "TransferToken to new contract") - public void test1TransferToNewContract() { - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAccountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1000L, contractAccountTokenBalance.longValue()); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "\"1" + "\",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "createContractTest(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(contractAddressA, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.longValue()); - } - - @Test(enabled = true, description = "TransferToken nonexistent target in constructor") - public void test2TransferToNonexistentTargetInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address,uint256,trcToken)"; - String argsStr = - "\"" + Base58.encode58Check(nonexistentAddress) + "\",\"1\",\"" + assetAccountId - .toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100,1000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(testNetAccountCountBefore.longValue() - 1000L, - testNetAccountCountAfter.longValue()); - Assert.assertEquals(999L, contractAccountCountAfter.longValue()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance.longValue()); - } - - @Test(enabled = true, description = "TransferToken existent target in constructor") - public void test3TransferToExistentTargetInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress3, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey3, blockingStubFull)); - - assetAccountId2 = PublicMethed.queryAccount(contractExcAddress3, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress3, assetAccountId2, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address,uint256,trcToken)"; - String argsStr = - "\"" + Base58.encode58Check(nonexistentAddress) + "\",\"1\",\"" + assetAccountId2 - .toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100, - 1000L, assetAccountId2.toStringUtf8(), 1000L, null, contractExcKey3, - contractExcAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress3, assetAccountId2, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(testNetAccountCountBefore.longValue() - 1000L, - testNetAccountCountAfter.longValue()); - Assert.assertEquals(999L, contractAccountCountAfter.longValue()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance.longValue()); - Long nonexistentAddressAccountTokenBalance2 = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId2, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance2.longValue()); - } - - @Test(enabled = true, description = "TransferToken existent target in constructor") - public void test4GetTokenBalanceInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(trcToken)"; - String argsStr = "\"" + assetAccountId.toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100,1000L, - "0", 0L, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java deleted file mode 100644 index 38e2a13e64d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java +++ /dev/null @@ -1,1684 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant001 { - - private final String testNetAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressNoAbi = null; - byte[] contractAddressWithAbi = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - private String fullnode1 = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private String soliditynode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(1); - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelRealSolidity = - ManagedChannelBuilder.forTarget(realSoliditynode).usePlaintext(true).build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - - { - Assert.assertTrue( - PublicMethed.sendcoin( - contractExcAddress, - 10000_000_000L, - testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - contractAddressNoAbi = - PublicMethed.deployContract( - contractName, - "[]", - code, - "", - maxFeeLimit, - 0L, - 100, - null, - contractExcKey, - contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = - PublicMethed.getContract(contractAddressNoAbi, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - contractAddressWithAbi = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - contractExcKey, - contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract2 = - PublicMethed.getContract(contractAddressWithAbi, blockingStubFull); - Assert.assertFalse(smartContract2.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract2.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract2.getBytecode().toString().isEmpty()); - } - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function without ABI") - public void test01TriggerConstantContract() { - - String txid = ""; - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - TransactionExtention transactionExtentionFromSolidity = - PublicMethed.triggerSolidityContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtentionFromSolidity.getResult().getCode()); - System.out.println( - "Message = " + transactionExtentionFromSolidity.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " without ABI on solidity") - public void test01TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " without ABI on real solidity") - public void test01TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " without ABI") - public void test02TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " without ABI on solidity") - public void test02TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a non-payable function" + " without ABI on real solidity") - public void test02TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a view function without ABI") - public void test03TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " without ABI on solidity") - public void test03TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " without ABI on real solidity") - public void test03TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function without ABI") - public void test04TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " without ABI on solidity") - public void test04TriggerConstantContractOnSolidity() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " without ABI on real solidity") - public void test04TriggerConstantContractOnRealSolidity() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function with ABI") - public void test05TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " with ABI on solidity") - public void test05TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " with ABI on real solidity") - public void test05TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "TriggerConstantContract a non-payable function with ABI") - public void test06TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " with ABI on solidity") - public void test06TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " with ABI on real solidity") - public void test06TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "TriggerConstantContract a view function with ABI") - public void test07TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " with ABI on solidity") - public void test07TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " with ABI on real solidity") - public void test07TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function with ABI") - public void test08TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " with ABI on solidity") - public void test08TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " with ABI on real solidity") - public void test08TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a payable function without ABI") - public void test09TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a non-payable function without ABI") - public void test10TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a view function without ABI") - public void test11TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a pure function without ABI") - public void test12TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a pure function with ABI") - public void test18TriggerContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a payable function with ABI") - public void test19TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = - PublicMethed.triggerContract( - contractAddressWithAbi, - "testPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a non-payable function with ABI") - public void test20TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI") - public void test21TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI on solidity") - public void test21TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI on real solidity") - public void test21TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view method with ABI ,method has " + "revert()") - public void test24TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method with ABI ,method has " + "revert() on solidity") - public void test24TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method with ABI ,method has " - + "revert() on real solidity") - public void test24TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerContract a view method with ABI ,method has " + "revert()") - public void test25TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerContract a view method with ABI ,method has " + "revert() on solidity") - public void test25TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerContract a view method with ABI ,method has " + "revert() on real solidity") - public void test25TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view method without ABI,method has" + "revert()") - public void testTriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method without ABI,method has" + "revert() on solidity") - public void testTriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method without ABI,method has" - + "revert() on real solidity") - public void testTriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java deleted file mode 100644 index cbfbef42dbe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function without ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java deleted file mode 100644 index e83946ff234..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java +++ /dev/null @@ -1,243 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - } - - @Test(enabled = true, description = "TriggerConstantContract a view function without ABI") - public void test001TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function without ABI") - public void test002TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function without ABI") - public void test003TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 1L, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - System.out.println(transactionExtention.toString()); - result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java deleted file mode 100644 index 6caa243b2c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a pure function without ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java deleted file mode 100644 index 82c1f52102d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java +++ /dev/null @@ -1,141 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a payable function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPayable()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java deleted file mode 100644 index 38fa2431758..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java deleted file mode 100644 index b2d4e06f49c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java deleted file mode 100644 index 252924f21fd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a pure function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java deleted file mode 100644 index 979e5d18ec7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a payable function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java deleted file mode 100644 index 9e945289276..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant010 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java deleted file mode 100644 index 23909e8bbf4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant011 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testView()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java deleted file mode 100644 index 96a6e807ef2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant012 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a pure function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testPure()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java deleted file mode 100644 index fd4e6144d80..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java +++ /dev/null @@ -1,338 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant013 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] returnAddressBytes = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode) - .usePlaintext(true) - .build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "triggerContract a constant function created by create2") - public void test01TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant015.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2") - public void test15TriggerConstantContract() { - - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on solidity") - public void test15TriggerConstantContractOnSolidity() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on real solidity") - public void test15TriggerConstantContractOnRealSolidity() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubRealSolidity); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on pbft") - public void test17TriggerConstantContractOnPbft() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubPbft); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java deleted file mode 100644 index 3e27bc60807..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant014 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] returnAddressBytes = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode).usePlaintext(true) - .build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - } - - @Test(enabled = true, description = "TriggerContract a non-constant function created by create2") - public void test01TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, "plusOne()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2") - public void test16TriggerConstantContract() { - - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, "plusOne()", "#", false, 0, - maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2 on solidity") - public void test16TriggerConstantContractOnSolidity() { - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2 on real solidity") - public void test16TriggerConstantContractOnRealSolidity() { - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java deleted file mode 100644 index 5444b9408ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java +++ /dev/null @@ -1,201 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant015 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a constant function " - + "created by create2") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant015.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java deleted file mode 100644 index 33fb1210db6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant016 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-constant function " - + "created by create2") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java deleted file mode 100644 index 8928e729b87..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant017 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function which is " - + "deployed with ABI, but cleared ABI later") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - String txid = ""; - txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - TransactionExtention transactionExtention1 = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction1 = transactionExtention1.getTransaction(); - - byte[] result1 = transactionExtention1.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction1.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention1.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result1)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result1)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java deleted file mode 100644 index 614a0ffb4fb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java +++ /dev/null @@ -1,151 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant018 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a pure function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testPure()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java deleted file mode 100644 index 05bdeffe04f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant019 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a payable function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, - "testPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java deleted file mode 100644 index 4846cc1a1e4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant020 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java deleted file mode 100644 index a33931489e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant021 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testView()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java deleted file mode 100644 index 1a2e0fbb35d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant022 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function " - + "with ABI(constant ABI)") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = "[{\"constant\":true,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\"," - + "\"type\":\"function\"}]"; - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java deleted file mode 100644 index 6ec25f0e2dc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant023 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function with" - + " ABI(constant ABI )") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = "[{\"constant\":true,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"name" - + "\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"" - + "type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"na" - + "me\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\"" - + ":\"function\"}]"; - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java deleted file mode 100644 index 4fc3a7470d6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant024 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method with ABI ,method has " - + "revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant024.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java deleted file mode 100644 index b2198f98698..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant025 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view method with ABI ,method has " - + "revert()") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant024.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert.assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java deleted file mode 100644 index 551d094b77e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java +++ /dev/null @@ -1,159 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant026 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method without ABI," - + "method has revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java deleted file mode 100644 index a548b370d42..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java +++ /dev/null @@ -1,159 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant027 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method without ABI," - + "method has revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java deleted file mode 100644 index bd3e67c2c4c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java +++ /dev/null @@ -1,254 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tryCatch; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class tryCatchTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - private byte[] errorContractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/tryCatch001.sol"; - String contractName = "tryTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - - contractName = "errorContract"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - errorContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - - @Test(enabled = true, description = "try catch revert no msg") - public void tryCatchTest001() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",0"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - - } - - @Test(enabled = true, description = "try catch revert msg") - public void tryCatchTest002() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",1"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("Revert Msg.", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch Require no msg") - public void tryCatchTest003() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",2"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Require msg") - public void tryCatchTest004() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("Require Msg.", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch assert") - public void tryCatchTest005() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",4"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch transfer fail") - public void tryCatchTest006() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",5"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Send_Error") - public void tryCatchTest007() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",6"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("success", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Math_Error") - public void tryCatchTest008() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",7"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch ArrayOverFlow_Error") - public void tryCatchTest009() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",8"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java deleted file mode 100644 index c55ba174d4f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java +++ /dev/null @@ -1,252 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tryCatch; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class tryCatchTest002 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - private byte[] errorContractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * miraculous.wong. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/tryCatch001.sol"; - String contractName = "tryTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - - - } - - - @Test(enabled = true, description = "try catch [new] revert no msg") - public void tryCatchTest001() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "0"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] revert msg") - public void tryCatchTest002() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "1"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] Require no msg") - public void tryCatchTest003() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "2"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Require msg") - public void tryCatchTest004() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] assert") - public void tryCatchTest005() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "4"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] transfer fail") - public void tryCatchTest006() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "5"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Send_Error") - public void tryCatchTest007() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "6"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertNotEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Math_Error") - public void tryCatchTest008() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "7"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch [new] ArrayOverFlow_Error") - public void tryCatchTest009() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "8"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java deleted file mode 100644 index 5556d5d0112..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java +++ /dev/null @@ -1,506 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeContractTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] testAddress003 = ecKey3.getAddress(); - String testKey003 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - private long freezeEnergyUseage; - private byte[] create2Address; - private final long freezeCount = 1000_123456L; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - PublicMethed.printAddress(testFoundationKey); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,10_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress003,12000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(description = "contract freeze to account") - void FreezeContractTest001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_before.getEnergyLimit() < account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - - } - - @Test(description = "contract freeze to self") - void FreezeContractTest002() { - AccountResourceMessage contractResource_before = PublicMethed - .getAccountResource(contractAddress,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage contractResource_after = PublicMethed - .getAccountResource(contractAddress,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + contractResource_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + contractResource_after.getEnergyLimit()); - Assert.assertTrue( - contractResource_before.getEnergyLimit() < contractResource_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance() + freezeCount, - contractAccount_after.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance()); - - } - - @Test(description = "contract freeze to other contract") - void FreezeContractTest003() { - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] newContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(newContract) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - Assert.assertEquals(TransactionInfo.code.FAILED,info.getResult()); - - AccountResourceMessage contractResource_after = PublicMethed - .getAccountResource(newContract,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + contractResource_after.getEnergyLimit()); - Assert.assertEquals(contractResource_after.getEnergyLimit(),0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(),contractAccount_after.getBalance()); - - } - - @Test(description = "contract freeze to unactive account", - dependsOnMethods = "FreezeContractTest001") - void FreezeContractTest004() { - - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey.getAddress(); - String testKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_after.getEnergyLimit() > 0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - // check active account status - Account testAccount = PublicMethed.queryAccount(testAddress,blockingStubFull); - Assert.assertTrue(testAccount.getCreateTime() > 0); - Assert.assertNotNull(testAccount.getOwnerPermission()); - Assert.assertNotNull(testAccount.getActivePermissionList()); - - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(freezeEnergyUseage + 25000L, info.getReceipt().getEnergyUsageTotal()); - - - } - - @Test(description = "contract freeze to pre create2 address, and UnFreeze", - dependsOnMethods = "FreezeContractTest001") - void FreezeContractTest005() { - String create2ArgsStr = "1"; - String create2MethedStr = "deploy(uint256)"; - TransactionExtention exten = PublicMethed.triggerConstantContractForExtention( - contractAddress, create2MethedStr, create2ArgsStr, false, 0, maxFeeLimit, - "#", 0, testAddress001, testKey001, blockingStubFull); - - String addressHex = - "41" + ByteArray.toHexString(exten.getConstantResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - create2Address = ByteArray.fromHexString(addressHex); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(create2Address,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_after.getEnergyLimit() > 0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(freezeEnergyUseage + 25000L, info.getReceipt().getEnergyUsageTotal()); - - txid = PublicMethed.triggerContract(contractAddress,create2MethedStr, - create2ArgsStr,false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - methedStr = "getExpireTime(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() - freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() + freezeCount, - contractAccount_after.getBalance()); - - } - - @Test(description = "Unfreeze when freeze to account", - dependsOnMethods = "FreezeContractTest001") - void UnFreezeContractTest001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "getExpireTime(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() - freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - - Assert.assertTrue(account002_before.getEnergyLimit() > account002_after.getEnergyLimit()); - - } - - @Test(description = "Unfreeze when freeze to contract self", - dependsOnMethods = "FreezeContractTest002") - void UnFreezeContractTest002() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "getExpireTime(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance() - freezeCount, - contractAccount_after.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance()); - - - } - - @Test(description = "energy caulate after transaction end") - public void freezeEnergyCaulate() { - - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - AccountResourceMessage testAccount001 = PublicMethed - .getAccountResource(testAddress001,blockingStubFull); - - - Assert.assertTrue(testAccount001.getEnergyLimit() > 0); - Assert.assertTrue(info.getReceipt().getEnergyFee() > 0); - Assert.assertTrue(testAccount001.getEnergyLimit() > info.getReceipt().getEnergyUsageTotal()); - - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testAddress001) + "\",1"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - testAccount001 = PublicMethed.getAccountResource(testAddress001,blockingStubFull); - - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - - Assert.assertEquals(0, info.getReceipt().getEnergyFee()); - Assert.assertEquals(0, testAccount001.getEnergyLimit()); - Assert.assertTrue(testAccount001.getEnergyUsed() > 0); - } - - @Test(description = "get Zero Address ExpirTime,used to be that freeze to contract self", - dependsOnMethods = "FreezeContractTest002") - public void getZeroExpireTimeTest() { - String ExpireTimeMethedStr = "getExpireTime(address,uint256)"; - String ExpireTimeArgsStr = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"" + ",0"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime1 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime1: " + ExpireTime1); - Assert.assertEquals(0,ExpireTime1.longValue()); - - ExpireTimeArgsStr = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"" + ",1"; - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime2 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime2: " + ExpireTime2); - Assert.assertEquals(0,ExpireTime2.longValue()); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertEquals((ExpireTime + 3) * 1000, info.getBlockTimeStamp()); - - - } - - @Test(description = "freeze in constructor") - public void FreezeContractTest006() { - - AccountResourceMessage account003_before = PublicMethed - .getAccountResource(testAddress003,blockingStubFull); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callValue = 10000_000000L; - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, callValue, - 100, null, testKey003, - testAddress003, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account003_after = PublicMethed - .getAccountResource(testAddress003,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account003_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account003_after.getEnergyLimit()); - Assert.assertTrue(account003_before.getEnergyLimit() < account003_after.getEnergyLimit()); - Assert.assertEquals(callValue, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(0, contractAccount_after.getBalance()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java deleted file mode 100644 index bb79702f0f0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java +++ /dev/null @@ -1,271 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeContractTest002 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long freezeEnergyUseage; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,10_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "contract freeze over balance") - void FreezeContract001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = contractAccount_before.getBalance() + 1; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertEquals(account002_before.getEnergyLimit(), account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - } - - @Test(enabled = true, description = "contract freeze amount < 1 TRX") - void FreezeContract002() { - - Account account002_before = PublicMethed - .queryAccount(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 999999L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account account002_after = PublicMethed - .queryAccount(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("account002_before.getAccountResource : " + account002_before.getAccountResource()); - logger.info("account002_after.getAccountResource : " + account002_after.getAccountResource()); - - Assert.assertEquals( - account002_before.getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(), - account002_after.getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - } - - @Test(enabled = true, description = "contract transfer all balance, then freeze") - void FreezeContract003() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = contractAccount_before.getBalance(); - String methedStr = "freezeAndSend(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertEquals(account002_before.getEnergyLimit(), account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - } - - @Test(enabled = true, description = "contract freeze to ger Net") - void FreezeContract004() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 1_000000L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "0"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getNetLimit : " + account002_before.getNetLimit()); - logger.info("account002_after.getNetLimit : " + account002_after.getNetLimit()); - Assert.assertTrue(account002_before.getNetLimit() < account002_after.getNetLimit()); - Assert.assertEquals(contractAccount_before - .getDelegatedFrozenBalanceForBandwidth() + freezeCount, - contractAccount_after.getDelegatedFrozenBalanceForBandwidth()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - } - - @Test(enabled = true, description = "contract freeze to ger Net") - void FreezeContract005() { - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 1000000L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String ExpireTimeMethedStr = "getExpireTime(address,uint256)"; - String ExpireTimeArgsStr = "\"" + Base58.encode58Check(testAddress001) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime1 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime1: " + ExpireTime1); - - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime2 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime2: " + ExpireTime2); - - // Test - Assert.assertEquals((ExpireTime2 + 3) * 1000, info.getBlockTimeStamp()); - // Online - // Assert.assertEquals((ExpireTime2.longValue() + 10800) * 1000, info.getBlockTimeStamp()); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java deleted file mode 100644 index e2b14c4277e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java +++ /dev/null @@ -1,290 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeSuicideTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long freezeEnergyUseage; - private long callValue; - private byte[] create2Address; - private final Long freezeCount = 1000_000000L; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,200_0000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - callValue = 50000_000000L; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, callValue, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(testAddress002, - 100_0000_000000L,0,0,testKey002,blockingStubFull)); - } - - @Test(enabled = true, description = "when delegate freeze, cannot suicide") - public void FreezeSuicideTest001() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + "1"; - PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - } - - @Test(enabled = true, description = "when delegate freeze to self, then suicide") - public void FreezeSuicideTest002() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - AccountResourceMessage freezeAccount_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + freezeCount + "," + "0"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage freezeAccount_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(freezeCount.longValue(), - contractAccount_after.getFrozen(0).getFrozenBalance()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - logger.info("freezeAccount_before.getNetLimit : " + freezeAccount_before.getNetLimit()); - logger.info("freezeAccount_after.getNetLimit : " + freezeAccount_after.getNetLimit()); - Assert.assertTrue(freezeAccount_after.getNetLimit() < freezeAccount_before.getNetLimit()); - - - Long beforeBalance = PublicMethed.queryAccount(testAddress002,blockingStubFull).getBalance(); - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - freezeAccount_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Assert.assertEquals(freezeAccount_before.getNetLimit(), - freezeAccount_after.getNetLimit()); - - Long AfterBalance = PublicMethed.queryAccount(testAddress002,blockingStubFull).getBalance(); - Assert.assertEquals(beforeBalance + callValue, AfterBalance.longValue()); - - - } - - @Test(enabled = true, description = "suicide、freeze、unfreeze、getExpireTime " - + "with suicided create2 address") - public void FreezeSuicideTest003() { - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String bytecode = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - callValue = 10000_000000L; - contractAddress = PublicMethed - .deployContract(contractName, abi, bytecode, "", maxFeeLimit, callValue, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // triggerconstant create2 function, and get create2 Address - String create2ArgsStr = "1"; - String create2MethedStr = "deploy(uint256)"; - TransactionExtention exten = PublicMethed.triggerConstantContractForExtention( - contractAddress, create2MethedStr, create2ArgsStr, false, 0, maxFeeLimit, - "#", 0, testAddress001, testKey001, blockingStubFull); - - String addressHex = - "41" + ByteArray.toHexString(exten.getConstantResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - create2Address = ByteArray.fromHexString(addressHex); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - // freeze to create2 Address, active create2 address - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - // create2 contract Address, turn create2 address to contract type - txid = PublicMethed.triggerContract(contractAddress,create2MethedStr, - create2ArgsStr,false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - - // create2 contract suicide - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(create2Address,methedStr,argsStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - // get create2 account ExpireTime - methedStr = "getExpireTime(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - // suicide FreezeTest contract, and should be failed - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - Account contract_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // unfreeze suicide create2 account - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + "1"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - Account contract_after = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(contract_before.getBalance() + freezeCount, contract_after.getBalance()); - Assert.assertEquals(contract_after.getAccountResource().getDelegatedFrozenBalanceForEnergy(), - contract_before.getAccountResource().getDelegatedFrozenBalanceForEnergy() - freezeCount); - - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java deleted file mode 100644 index 207406b58ca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "tokenIssue normal") - public void tokenIssueNormal() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - /*String param = "0000000000000000000000000000000000007465737441737365744973737565" - + "0000000000000000000074657374417373657431353938333439363637393631" - + "0000000000000000000000000000000000000000000000000000000000989680" - + "0000000000000000000000000000000000000000000000000000000000000001";*/ - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - } - - @Test(enabled = false, description = "updateAsset normal") - public void updateAssetNormal() { - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - String txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java deleted file mode 100644 index 2b7e693fa91..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java +++ /dev/null @@ -1,744 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String assetIssueId = null; - long contractAddressBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "tokenIssue illegal parameter verification") - public void tokenIssue001IllegalParameterVerification() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 2050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - /*String param = "0000000000000000000000000000000000007465737441737365744973737565" - + "0000000000000000000074657374417373657431353938333439363637393631" - + "0000000000000000000000000000000000000000000000000000000000989680" - + "0000000000000000000000000000000000000000000000000000000000000001";*/ - // assetName is trx - String tokenName = PublicMethed.stringToHexString("trx"); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetName.length > 32 compile fail - /*tokenName = PublicMethed.stringToHexString("testAssetIssue_testAssetIssue_tes"); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size());*/ - - // assetName is "" - tokenName = PublicMethed.stringToHexString(""); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetName is chinese - tokenName = PublicMethed.stringToHexString("名字"); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is null - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(""); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is chinese - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("简称"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is Long.MAX_VALUE+1 - param = "a8547918" - + "74657374417373657449737375655f3136303034333636393333333600000000" - + "7472780000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000008000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000006"; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is -1 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + -1 + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - logger.info("totalSupply is -1"); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCCESS", infoById.get().getReceipt().getResult().toString()); - Assert.assertTrue(infoById.get().getFee() < 1000000000); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is 0 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + 0 + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - logger.info("totalSupply is 0"); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCCESS", infoById.get().getReceipt().getResult().toString()); - Assert.assertTrue(infoById.get().getFee() < 1000000000); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // precision is 7 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 7; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // precision is -1 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + -1; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is trx will success - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals("trx", ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - - // created multiple times will fail - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - String assetIssueId1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - Assert.assertEquals(assetIssueId, assetIssueId1); - } - - @Test(enabled = false, description = "tokenIssue trx balance insufficient") - public void tokenIssue002TrxBalanceInsufficient() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1023999999L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // trx balance insufficient - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - } - - @Test(enabled = false, description = "tokenIssue called multiple times in one contract") - public void tokenIssue003CalledMultipleTimesInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue002.sol"; - String contractName = "tvmAssetIssue002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 5; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(5, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue revert") - public void tokenIssue004Revert() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue003.sol"; - String contractName = "tvmAssetIssue003"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 2500000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 4; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(4, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - String tokenName1 = PublicMethed.stringToHexString(name + "_rev"); - String tokenAbbr1 = PublicMethed.stringToHexString(abbr + "_rev"); - param = - "\"" + tokenName1 + "\",\"" + tokenAbbr1 + "\",\"" + 1000000 + "\",\"" + 3 + "\",\"" - + Base58.encode58Check(dev002Address) + "\""; - logger.info("param: " + param); - String methodTokenIssueRevert = "tokenIssueAndTransfer(bytes32,bytes32,uint64,uint8,address)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssueRevert, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - String assetIssueId1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId1: " + assetIssueId1); - Assert.assertEquals(assetIssueId, assetIssueId1); - assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(4, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long balance = PublicMethed.queryAccount(dev002Address, blockingStubFull).getBalance(); - Assert.assertEquals(200000000L, balance); - } - - @Test(enabled = false, description = "tokenIssue call another contract in one contract") - public void tokenIssue005CallAnotherInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue004.sol"; - String contractName = "tvmAssetIssue004"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1030000000L; - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - callvalue = 1024000000L; - String txid = PublicMethed.triggerContract(contractAddress, "getContractAddress()", "#", false, - callvalue, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - contractAddressBalance = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 2; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - long assetIssueValue = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddressA, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java deleted file mode 100644 index 60ca55d3666..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java +++ /dev/null @@ -1,864 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue003 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "updateAsset illegal parameter verification") - public void updateAsset001IllegalParameterVerification() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // desc and url is trx, will success - url = "trx"; - description = "trx"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is 201, will fail - String descriptions = - "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890" - + "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc" - + "_1234567890" - + "desc_1234567890desc_1234567890desc_1"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + descriptions + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is "", will success - param = "\"" + assetIssueId + "\",\"" + url + "\",\"\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is chinese, will success - description = "token说明"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is 257, will fail - String urls = - "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901" - + "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901url" - + "_12345678901" - + "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901ur"; - param = "\"" + assetIssueId + "\",\"" + urls + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is "", will fail - param = "\"" + assetIssueId + "\",\"\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is chinese, will success - url = "官网"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset called multiple times in one contract") - public void updateAsset002CalledMultipleTimesInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue002.sol"; - String contractName = "tvmAssetIssue002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("infoById: " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - description = "desc1_" + Long.toString(now); - url = "url1_" + Long.toString(now); - String description2 = "desc2_" + Long.toString(now); - String url2 = "url2_" + Long.toString(now); - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\",\"" + url2 + "\",\"" - + description2 + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description2, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url2, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset revert") - public void updateAsset003Revert() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue003.sol"; - String contractName = "tvmAssetIssue003"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1225000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("infoById: " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - String description1 = - "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890" - + "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc" - + "_1234567890" - + "desc_1234567890desc_1234567890desc_1"; - String url1 = "url1_" + Long.toString(now); - param = "\"" + assetIssueId + "\",\"" + url1 + "\",\"" + description1 + "\",\"" + Base58 - .encode58Check(dev002Address) + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAssetAndTransfer(trcToken,string,string,address)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(0, assetIssueById.getUrl().size()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long balance = PublicMethed.queryAccount(dev002Address, blockingStubFull).getBalance(); - Assert.assertEquals(200000000L, balance); - } - - @Test(enabled = false, description = "updateAsset call another contract in one contract") - public void updateAsset004CallAnotherInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue004.sol"; - String contractName = "tvmAssetIssue004"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1030000000L; - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - callvalue = 1024000000L; - String txid = PublicMethed.triggerContract(contractAddress, "getContractAddress()", "#", false, - callvalue, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - long contractAddressBalance = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 2; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - long assetIssueValue = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset verify token") - public void updateAsset005VerifyTokenId() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(dev002Address, 50_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // token id does not exist, will update myself - url = "trx"; - description = "trx"; - param = "\"1119125\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // not owner's asset, will update myself - AssetIssueContract assetIssueByIdBefore = PublicMethed - .getAssetIssueById("1000004", blockingStubFull); - final String nameBefore = ByteArray.toStr(assetIssueByIdBefore.getName().toByteArray()); - final String abbrBefore = ByteArray.toStr(assetIssueByIdBefore.getAbbr().toByteArray()); - final String descBefore = assetIssueByIdBefore.getDescription().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdBefore.getDescription().toByteArray()); - final String urlBefore = assetIssueByIdBefore.getUrl().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdBefore.getUrl().toByteArray()); - final long precisionBefore = assetIssueByIdBefore.getPrecision(); - url = url + "123456"; - description = description + "123"; - param = "\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed - .triggerContract(contractAddress, "updateOtherAccountAsset(string,string)", param, false, - 0, maxFeeLimit, dev002Address, dev002Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - AssetIssueContract assetIssueByIdAfter = PublicMethed - .getAssetIssueById("1000004", blockingStubFull); - String descAfter = assetIssueByIdBefore.getDescription().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdAfter.getDescription().toByteArray()); - String urlAfter = assetIssueByIdBefore.getUrl().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdAfter.getUrl().toByteArray()); - Assert.assertEquals(nameBefore, ByteArray.toStr(assetIssueByIdAfter.getName().toByteArray())); - Assert.assertEquals(abbrBefore, ByteArray.toStr(assetIssueByIdAfter.getAbbr().toByteArray())); - Assert.assertEquals(descBefore, descAfter); - Assert.assertEquals(urlBefore, urlAfter); - Assert.assertEquals(precisionBefore, assetIssueByIdAfter.getPrecision()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java deleted file mode 100644 index 9bf181a4c48..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue004 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] dev003Address = ecKey3.getAddress(); - private String dev003Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - PublicMethed.printAddress(dev003Key); - } - - @Test(enabled = false, description = "tokenIssue and transfer to account") - public void tokenIssueAndTransferToAccount() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // transfer token to create exist account - Assert.assertTrue(PublicMethed - .sendcoin(dev003Address, 10_000_000L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long dev001AddressBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceBefore: " + dev001AddressBalanceBefore); - param = "\"" + Base58.encode58Check(dev003Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long dev001AddressBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceAfter: " + dev001AddressBalanceAfter); - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev003AssetValue = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev003AssetValue); - - // transfer token to create new account - long dev001AddressBalanceBefore1 = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceBefore1: " + dev001AddressBalanceBefore1); - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 30000); - long dev001AddressBalanceAfter2 = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceAfter2: " + dev001AddressBalanceAfter2); - long assetIssueValueAfter1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter - 100L, assetIssueValueAfter1); - Assert.assertEquals(100L, dev002AssetValue); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java deleted file mode 100644 index ba61000f6a6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java +++ /dev/null @@ -1,703 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue005 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - private long contractAddressBalance; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] dev003Address = ecKey3.getAddress(); - private String dev003Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - private byte[] dev004Address = ecKey4.getAddress(); - private String dev004Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - PublicMethed.printAddress(dev003Key); - PublicMethed.printAddress(dev004Key); - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 7000_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset with suicide to account") - public void tokenIssue001AndSuicideToAccount() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "tvmAssetIssue005"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - // deploy - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // tokenIssue - name = "testAssetIssu1_" + Long.toString(now); - abbr = "testAsse1_" + Long.toString(now); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - AssetIssueContract assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - AssetIssueContract assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress, blockingStubFull).get().getAssetIssue(0); - AssetIssueContract assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // transferToken - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - - // updateAsset - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // selfdestruct - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(dev003Address) + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID().size()); - Assert.assertEquals(0, - PublicMethed.getAssetIssueByAccount(dev003Address, blockingStubFull).get() - .getAssetIssueCount()); - Assert.assertEquals(0, - PublicMethed.queryAccount(dev003Address, blockingStubFull).getAssetIssuedID().size()); - long contractAssetCountDev003 = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter, contractAssetCountDev003); - assetIssueValue = PublicMethed.queryAccount(dev003Address, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(assetIssueValueAfter, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress, blockingStubFull).get().getAssetIssue(0); - assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(100L, dev002AssetValue); - - Assert.assertTrue(PublicMethed - .sendcoin(dev002Address, 100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // transferAsset,success - Assert.assertTrue(PublicMethed.transferAsset(dev002Address, assetIssueId.getBytes(), 100L, - dev003Address, dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002 = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev003 = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(200L, assetIssueValueDev002); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueDev003); - - Assert.assertTrue(PublicMethed.transferAsset(dev004Address, assetIssueId.getBytes(), 102L, - dev002Address, dev002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002After = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev004 = PublicMethed - .getAssetIssueValue(dev004Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(102L, assetIssueValueDev004); - Assert.assertEquals(assetIssueValueDev002 - 102L, assetIssueValueDev002After); - - // updateAsset,will fail - Assert.assertFalse(PublicMethed - .updateAsset(dev003Address, "updateDesc1".getBytes(), "updateURL1".getBytes(), 1L, 2L, - dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertFalse(PublicMethed - .updateAsset(contractAddress, "updateDesc2".getBytes(), "updateURL2".getBytes(), 3L, 4L, - dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset with suicide to contract") - public void tokenIssue002AndSuicideToContract() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "tvmAssetIssue005"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - // deploy - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress2, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance2); - - deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // tokenIssue - name = "testAssetIssu2_" + Long.toString(now); - abbr = "testAsse2_" + Long.toString(now); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress2, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - AssetIssueContract assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - AssetIssueContract assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress2, blockingStubFull).get().getAssetIssue(0); - AssetIssueContract assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - long contractAddressBalanceAfter2 = PublicMethed - .queryAccount(contractAddress2, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance2 - 1024000000L, contractAddressBalanceAfter2); - - // transferToken - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress2, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - - param = - "\"" + Base58.encode58Check(contractAddress) + "\"," + 50 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress2, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long assetIssueValueAfter2 = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long contractAssetValue = PublicMethed - .getAssetIssueValue(contractAddress, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter - 50L, assetIssueValueAfter2); - Assert.assertEquals(50L, contractAssetValue); - - // selfdestruct - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(contractAddress) + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress2, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress2, blockingStubFull).getAssetIssuedID().size()); - Assert.assertEquals(0, - PublicMethed.getAssetIssueByAccount(contractAddress, blockingStubFull).get() - .getAssetIssueCount()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID().size()); - assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(assetIssueValueAfter2 + 50L, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress2, blockingStubFull).get().getAssetIssue(0); - assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - - // transferToken,success - methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(200L, dev002AssetValue); - - Assert.assertTrue(PublicMethed.transferAsset(dev004Address, assetIssueId.getBytes(), 12L, - dev002Address, dev002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002After = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev004 = PublicMethed - .getAssetIssueValue(dev004Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(12L, assetIssueValueDev004); - Assert.assertEquals(dev002AssetValue - 12L, assetIssueValueDev002After); - - // updateAsset,will fail - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"" + assetIssueId + "\",\"updateUrl\",\"updateDesc\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(0, assetIssueById.getUrl().size()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset suicide with create2") - public void tokenIssue003AndSuicideWithCreate2() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String methodTokenIssue = "deploy(uint256)"; - String param = "" + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - logger.info("actualSalt: " + actualSalt); - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), - 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - byte[] callContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - Assert.assertTrue(PublicMethed - .sendcoin(callContractAddress, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - name = "testAssetIssu3_" + Long.toString(now); - abbr = "testAsse3_" + Long.toString(now); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(dev003Address) + "\"," + 10000000; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - methodTokenIssue = "deploy(uint256)"; - param = "" + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(callContractAddress, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - tokenName = PublicMethed.stringToHexString("testAssetIssue_11111"); - tokenAbbr = PublicMethed.stringToHexString("testAssetIssue_22222"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - String assetIssueId2 = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId2: " + assetIssueId2); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId2)); - Assert.assertEquals(Long.parseLong(assetIssueId) + 1, Long.parseLong(assetIssueId2)); - Assert.assertEquals(2, - PublicMethed.getAssetIssueByAccount(callContractAddress, blockingStubFull).get() - .getAssetIssueCount()); - - // updateAsset - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"123\",\"updateURLURL\",\"updateDESCDESC\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnId); - String newAssetIssueId = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("newAssetIssueId: " + newAssetIssueId); - AssetIssueContract newAssetIssueById = PublicMethed - .getAssetIssueById(newAssetIssueId, blockingStubFull); - Assert.assertEquals("testAssetIssue_11111", - ByteArray.toStr(newAssetIssueById.getName().toByteArray())); - Assert.assertEquals("testAssetIssue_22222", - ByteArray.toStr(newAssetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals("updateDESCDESC", - ByteArray.toStr(newAssetIssueById.getDescription().toByteArray())); - Assert.assertEquals("updateURLURL", ByteArray.toStr(newAssetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, newAssetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(callContractAddress), - Base58.encode58Check(newAssetIssueById.getOwnerAddress().toByteArray())); - - AssetIssueContract oldAssetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(oldAssetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(oldAssetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, oldAssetIssueById.getDescription().size()); - Assert.assertEquals(0, oldAssetIssueById.getUrl().size()); - Assert.assertEquals(6, oldAssetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(callContractAddress), - Base58.encode58Check(oldAssetIssueById.getOwnerAddress().toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java deleted file mode 100644 index 2dbc0b54cf9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractRewardTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String witnessKey = Configuration.getByPath("testng.conf").getString("witness.key1"); - private String witnessAddress = PublicMethed.getAddressString(witnessKey); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - //= Base58.decode58Check("TQYK8QPAFtxjmse1dShHWYXEMsF836jxxe"); - - @BeforeSuite(enabled = false, description = "stake beforeSuite delete") - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/stackContract001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000_000L, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + witnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - } - - @Test(enabled = false,description = "querry SR account, reward should equal to gerRewardInfo") - void rewardbalanceTest001() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(PublicMethed.getFinalAddress(witnessKey))) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + witnessAddress + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - System.out.println(txen); - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(reward,rewardBalance); - } - - @Test(enabled = false,description = "querry 0x00, reward should be 0") - void rewardbalanceTest002() { - String methedStr = "nullAddressTest()"; - String argStr = ""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,0); - } - - @Test(enabled = false,description = "querry UnActive account , reward should be 0") - void rewardbalanceTest003() { - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + PublicMethed.getAddressString(key) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,0); - } - - @Test(enabled = false,description = "querry contract account,reward should equal to " - + "gerRewardInfo") - void rewardbalanceTest004() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(contractAddress)) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - logger.info("rewardBalance: " + rewardBalance); - logger.info("reward: " + reward); - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,reward); - } - - @Test(enabled = false,description = "querry ZeroReward account, reward should be 0") - void rewardbalanceTest005() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(PublicMethed.getFinalAddress(testFoundationKey))) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + PublicMethed.getAddressString(testFoundationKey) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(reward,rewardBalance,0); - } - - @Test(enabled = false,description = "withdrawBalance") - void withdrawBalanceTest006() { - //contractAddress = Base58.decode58Check("TBsf2FCSht83CEA8CSZ1ReQTRDByNB7FCe"); - - String methedStr = "withdrawRewardTest()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - - @Test(enabled = false,description = "withdrawBalance twice") - void withdrawBalanceTest007() { - String methedStr = "withdrawRewardTest()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - - @Test(enabled = false,description = "withdrawBalance other contract") - void withdrawBalanceTest008() { - String filePath = "src/test/resources/soliditycode/stackContract001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] otherContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000_000L, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - String methedStr = "contractBWithdrawRewardTest(address)"; - String argStr = "\"" + Base58.encode58Check(otherContract) + "\""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), TransactionInfo.code.SUCESS); - } - - @Test(enabled = false,description = "new withdrawBalance constructor") - void withdrawBalanceTest009() { - String methedStr = "createA()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - - int result = ByteArray.toInt(ext.getLog(0).getData().toByteArray()); - Assert.assertEquals(result,0); - int result2 = ByteArray.toInt(ext.getLog(1).getData().toByteArray()); - Assert.assertEquals(result2,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java deleted file mode 100644 index c1a3d68992e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java +++ /dev/null @@ -1,118 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class IsSrCandidateTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/isSRCandidate.sol"; - String contractName = "TestIsSRCandidate"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = false, description = "Witness Address should be true") - void tvmStakeTest001() { - String methodStr = "isSRCandidateTest(address)"; - String argsStr = "\"" + PublicMethed.getAddressString(testWitnessKey) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,1); - } - - @Test(enabled = false, description = "Account Address should be false") - void tvmStakeTest002() { - String methodStr = "isSRCandidateTest(address)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - - @Test(enabled = false, description = "zero Address(0x00) should be false") - void tvmStakeTest003() { - String methodStr = "zeroAddressTest()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - - @Test(enabled = false, description = "Contract Address should be false") - void tvmStakeTest004() { - String methodStr = "localContractAddrTest()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java deleted file mode 100644 index f1a43ad8e49..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java +++ /dev/null @@ -1,247 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StackSuicideTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = false, description = "targetAddress no TRX, and no frozen") - public void stackSuicideTest001() { - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, 100, null, testKey001, - testAddress001, blockingStubFull); - - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0, 100, null, testKey001, testAddress001, blockingStubFull); - - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has TRX, but no frozen") - public void stackSuicideTest002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, 100, null, testKey001, - testAddress001, blockingStubFull); - - - Long targetBalance = 10_000_000L; - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, targetBalance, 100, null, testKey001, testAddress001, blockingStubFull); - - String methedStr = "Stake(address,uint256)"; - String argStr = "\"" + testWitnessAddress + "\",10000000"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr, - argStr,false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - methedStr = "transfer(address,uint256)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + targetBalance; - txid = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(0,PublicMethed.queryAccount(targetAddress,blockingStubFull).getBalance()); - } - - @Test(enabled = false, description = "targetAddress has TRX, and has frozen") - public void stackSuicideTest003() { - Long targetBalance = 10_000_000L; - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, targetBalance, 100, - null, testKey001, testAddress001, blockingStubFull); - - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 12_345_678L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methedStr = "Stake(address,uint256)"; - String argStr = "\"" + testWitnessAddress + "\"," + targetBalance; - String txid = PublicMethed.triggerContract(contractAddress,methedStr, - argStr,false,0,maxFeeLimit, testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - argStr = "\"" + testWitnessAddress + "\"," + 12_000_000L; - String txid2 = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid2,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozen = targetAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccount.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozen.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozen.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozen.getFrozenBalance()); - - methedStr = "transfer(address,uint256)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + 345678; - txid = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(0,PublicMethed.queryAccount(targetAddress,blockingStubFull).getBalance()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java deleted file mode 100644 index 2856b2d436c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StakeSuicideTest002 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "create2 -> stake -> suicide -> create2 the same Address") - public void stackSuicideAndCreate2Test001() { - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methedStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + 1; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String hex = "41" + ByteArray.toHexString(ex.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("Deploy Address : " + Base58.encode58Check(ByteArray.fromHexString(hex))); - byte[] ownerAddress = ByteArray.fromHexString(hex); - - methedStr = "Stake(address,uint256)"; - argStr = "\"" + testWitnessAddress + "\"," + 10_000_000; - txid = PublicMethed.triggerContract(ownerAddress,methedStr, - argStr,false,10_000_000,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(ownerAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methedStr = "deploy(bytes,uint256)"; - argStr = "\"" + code + "\"," + 1; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - Assert.assertEquals(ownerAccount.getBalance(),0); - Assert.assertEquals(ownerAccount.getFrozenCount(),0); - Assert.assertEquals(ownerAccount.getVotesCount(),0); - - Account targetAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "create2 -> stake -> suicide -> sendcoin to create2 Address") - public void stackSuicideAndCreate2Test002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methedStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + 2; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String hex = "41" + ByteArray.toHexString(ex.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("Deploy Address : " + Base58.encode58Check(ByteArray.fromHexString(hex))); - byte[] ownerAddress = ByteArray.fromHexString(hex); - - methedStr = "Stake(address,uint256)"; - argStr = "\"" + testWitnessAddress + "\"," + 10_000_000; - txid = PublicMethed.triggerContract(ownerAddress,methedStr, - argStr,false,10_000_000,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\""; - txid = PublicMethed.triggerContract(ownerAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long sendcoin = 1; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress,sendcoin,testFoundationAddress, - testFoundationKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - Assert.assertEquals(ownerAccount.getBalance(),sendcoin); - Assert.assertEquals(ownerAccount.getFrozenCount(),0); - Assert.assertEquals(ownerAccount.getVotesCount(),0); - - Account targetAccount = PublicMethed.queryAccount(testAddress001,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java deleted file mode 100644 index 6393aece552..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest003 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(testAddress001,10000000,testFoundationAddress, - testFoundationKey,blockingStubFull); - } - - @Test(enabled = false, description = "suicide target Address is owner Address") - public void stakeSuicideTest001() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - } - - @Test(enabled = false, description = "suicide target Address is BlackHoleAddress Address") - public void stakeSuicideTest002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String blackHoleAddress = "TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy"; - final Account accountBefore = PublicMethed - .queryAccount(PublicMethed.decode58Check(blackHoleAddress), - blockingStubFull); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + blackHoleAddress + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - Account accountAfter = PublicMethed - .queryAccount(PublicMethed.decode58Check(blackHoleAddress), - blockingStubFull); - Assert.assertEquals(accountBefore.getBalance() + ex.get().getReceipt().getEnergyFee() - + 10000000, accountAfter.getBalance()); - } - - @Test(enabled = false, description = "suicide target Address is BlackHoleAddress Address") - public void stakeSuicideTest003() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - final Account accountBefore = PublicMethed - .queryAccount(PublicMethed.decode58Check("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"), - blockingStubFull); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - Account accountAfter = PublicMethed - .queryAccount(PublicMethed.decode58Check("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"), - blockingStubFull); - Assert.assertEquals(accountBefore.getBalance() + 10000000, accountAfter.getBalance()); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java deleted file mode 100644 index 69bcbcff619..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java +++ /dev/null @@ -1,397 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest004 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - String code = ""; - String abi = ""; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - System.out.println(testKey001); - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000_000000L, 100, - null, testKey001, testAddress001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "targetAddress has frozen 1,suicide contract stake 1") - void tvmStakeSuicideTest001() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has frozen 1,suicide contract stake all") - void tvmStakeSuicideTest002() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has frozen all,suicide contract stake all") - void tvmStakeSuicideTest003() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 20_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(targetAddress,5_000000L, - 3,1, ByteString.copyFrom(testAddress001),testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,10_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress is new account ,suicide contract stake all") - void tvmStakeSuicideTest004() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - System.out.println(Base58.encode58Check(targetAddress)); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress frozen to other address ,suicide contract " - + "stake all") - void tvmStakeSuicideTest005() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] address = ecKey.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(targetAddress,5_000000L, - 3,1, ByteString.copyFrom(testAddress001),testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - System.out.println("aaaa" + Base58.encode58Check(targetAddress)); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - System.out.println("aaaaa" + Base58.encode58Check(contractAddress)); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenAfter = targetAccount.getFrozen(0); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Assert.assertEquals(ownerFrozen.getExpireTime(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance()); - - } - - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java deleted file mode 100644 index b324672d6ab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest005 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - String code = ""; - String abi = ""; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - @BeforeClass(enabled = false) - public void beforeClass() { - System.out.println(testKey001); - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "targetAddress is account no TRX, and no frozen") - void tvmStakeSuicideTest001() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000_000000L, 100, - null, testKey001, testAddress001, blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Long targetBalance = targetAccount.getBalance(); - - System.out.println(targetBalance); - Assert.assertEquals(ownerBalance,targetBalance); - - } - - @Test(enabled = false, description = "targetAddress is account 1 TRX, and no frozen") - void tvmStakeSuicideTest002() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - final String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - - PublicMethed - .sendcoin(targetAddress, 1_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Long targetBalance = targetAccount.getBalance() - 1_000000L; - - Assert.assertEquals(ownerBalance,targetBalance); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = false, description = "targetAddress is account 1 TRX, and 1 frozen") - void tvmStakeSuicideTest003() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - Long targetBalance = targetAccountAfter.getBalance() - 9_000000L; - Assert.assertEquals(targetFrozenBefore,targetFrozenAfter); - Assert.assertEquals(ownerBalance,targetBalance); - - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java deleted file mode 100644 index 4b9102fc901..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java +++ /dev/null @@ -1,312 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StakeTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000_0000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Vote for witness") - void tvmStakeTest001() { - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - long balanceAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - Assert.assertEquals(balanceAfter,balanceBefore - 1000000); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - Assert.assertEquals(1,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - - - } - - @Test(enabled = false, description = "Non-witness account") - void tvmStakeTest002() { - //account address - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,0); - - //contract address - methodStr = "Stake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + 1000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,0); - - - } - - - @Test(enabled = false, description = "Number of votes over balance") - void tvmStakeTest003() { - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + Long.MAX_VALUE; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - - Assert.assertEquals(contractResult,0); - - } - - - @Test(enabled = false, description = "Enough votes for a second ballot") - void tvmStakeTest004() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 21000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - System.out.println(blockingStubFull.getAccount(request).getVotesCount()); - Assert.assertEquals(21,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 11000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0).getVoteAddress() - .toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - Assert.assertEquals(11,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - } - - - @Test(enabled = false, description = "Revert test") - void tvmStakeTest005() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "revertTest1(address,uint256,address)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000 + ",\"" - + Base58.encode58Check(testAddress001) + "\""; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - - Assert.assertEquals(contractResult,0); - - } - - - @Test(enabled = false, description = "Contract Call Contract stake") - void tvmStakeTest006() { - String methodStr = "deployB()"; - String argsStr = ""; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("txid:" + txid); - - methodStr = "BStake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long callvalue = 1000000000L; - txid = PublicMethed.triggerContract(contractAddress, "deployB()", "#", false, - callvalue, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - byte[] contractAddressB = ByteArray.fromHexString(addressHex); - long contractAddressBBalance = PublicMethed.queryAccount(contractAddressB, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBBalance); - - methodStr = "BStake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - long balanceAfter = account.getBalance(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - Assert.assertEquals(balanceAfter, contractAddressBBalance - 10000000); - - } - - @Test(enabled = false, description = "Vote for the first witness and then vote for the second " - + "witness.") - void tvmStakeTest007() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 21000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - System.out.println(blockingStubFull.getAccount(request).getVotesCount()); - Assert.assertEquals(21,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - argsStr = "\"" + Base58.encode58Check(testWitnessAddress2) + "\"," + 11000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0).getVoteAddress() - .toByteArray()); - Assert.assertEquals(testWitnessAddress2,voteAddress); - Assert.assertEquals(11,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java deleted file mode 100644 index be418169c53..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java +++ /dev/null @@ -1,471 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class UnStakeTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] testAddress002 = ecKey2.getAddress(); - private String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false, description = "unstake normal") - public void tvmStakeTest001Normal() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "unStake()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "#", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - } - - @Test(enabled = false, description = "unstake when no stake") - public void tvmUnstakeTest002NoStake() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "unStake()"; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - Assert.assertEquals(account.getBalance(), balanceBefore); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - } - - @Test(enabled = false, description = "unstake twice") - public void tvmUnstakeTest003UnstakeTwice() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "unStake2()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - } - - @Test(enabled = false, description = "unstake revert") - public void tvmUnstakeTest004Revert() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "revertTest2(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), 993000000L); - long balance = PublicMethed.queryAccount(testAddress002, blockingStubFull).getBalance(); - Assert.assertEquals(7000000L, balance); - } - - @Test(enabled = false, description = "unstake call another contract in one contract") - public void tvmUnstakeTest005CallAnotherInOneContract() { - PublicMethed - .sendcoin(testAddress001, 2120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long callvalue = 1000000000L; - String txid = PublicMethed.triggerContract(contractAddress, "deployB()", "#", false, - callvalue, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressB = ByteArray.fromHexString(addressHex); - logger.info("contractAddressB: " + Base58.encode58Check(contractAddressB)); - long contractAddressBBalance = PublicMethed.queryAccount(contractAddressB, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBBalance); - - String methodStr = "BStake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - long balanceAfter = account.getBalance(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - Assert.assertEquals(balanceAfter, contractAddressBBalance - 10000000); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance, 1000000000); - - methodStr = "BUnStake()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), contractAddressBBalance); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance, 1000000000); - } - - @Test(enabled = false, description = "unstake with reward balance") - public void tvmUnstakeTest006WithRewardBalance() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methodStr = "rewardBalance(address)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, false, 0, 0, "0", - 0, testAddress001, testKey001, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - org.junit.Assert.assertEquals(0, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - methodStr = "withdrawReward()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter2 = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceAfter2); - - methodStr = "unStake2()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - - methodStr = "rewardBalance(address)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, false, 0, 0, "0", - 0, testAddress001, testKey001, blockingStubFull); - transaction = transactionExtention.getTransaction(); - result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - org.junit.Assert.assertEquals(0, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(testAddress001, testKey001, testFoundationAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java deleted file mode 100644 index 32d378c4d83..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java +++ /dev/null @@ -1,506 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TestValidatemultisign001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - ECKey ecKey004 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey004.getAddress(); - String participateKey = ByteArray.toHexString(ecKey004.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(address) case") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - // Trigger with correct Permission address - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with wrong Permission address - merged = ByteUtil.merge(dev001Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(dev001Address), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with address that have not permission - merged = ByteUtil.merge(fromAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(fromAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with not exist address - merged = ByteUtil.merge(manager1Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(manager1Address), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with error format address - merged = ByteUtil.merge(manager1Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList("TVgXWwGWE9huXiE4FuzDuGnCPUowsbZ8VZ", - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(permissionId) case") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - // Trigger with wrong PermissionID - long permissionId = 2; - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with error format PermissionID - permissionId = 100; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Long.MAX_VALUE + 1 PermissionID - permissionId = Long.MAX_VALUE + 1; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Long.MIN_VALUE - 1 PermissionID - permissionId = Long.MIN_VALUE - 1; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(hash) case") - public void test004validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, 0, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - // Trigger with no sign hash - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with wrong hash - transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, 0, ownerKey, blockingStubFull); - logger.info("hash: {}", Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes()); - - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // 1) address B create transaction_1, but address A`s permission address sign - // 2) user address A verify transaction_1 that created by B - transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, dev001Address, 0, dev001Key, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java deleted file mode 100644 index 8898e687459..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java +++ /dev/null @@ -1,378 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TestValidatemultisign002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - ECKey ecKey004 = new ECKey(Utils.getRandom()); - byte[] manager4Address = ecKey004.getAddress(); - String manager4Key = ByteArray.toHexString(ecKey004.getPrivKeyBytes()); - ECKey ecKey005 = new ECKey(Utils.getRandom()); - byte[] manager5Address = ecKey005.getAddress(); - String manager5Key = ByteArray.toHexString(ecKey005.getPrivKeyBytes()); - ECKey ecKey006 = new ECKey(Utils.getRandom()); - byte[] manager6Address = ecKey006.getAddress(); - String manager6Key = ByteArray.toHexString(ecKey006.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager4Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager5Key) + "\",\"weight\":1}," - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign with signatures num") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - - // Trigger with one signature - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with five signature - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with six signature - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey006.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign with Duplicate signatures") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - // signatures with Duplicate signatures but weight enough - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Duplicate signatures and weight not enough - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Duplicate signatures and fix signatures - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign with weight") - public void test004validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - // signatures with weight not enough - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java deleted file mode 100644 index 840c86c0102..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java +++ /dev/null @@ -1,242 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Sha256Hash; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class TestValidatemultisign003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign precompiled contract, " - + "with wrong hash bytes") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String argsStr = PublicMethed.parametersString(parameters); - - byte[] inputBytesArray = Hex.decode(AbiUtil.parseMethod( - "validatemultisign(address,uint256,bytes32,bytes[])", argsStr, false)); - String input = ByteArray.toHexString(inputBytesArray); - - String methodStr = "testMultiPrecompileContract(bytes)"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, - AbiUtil.parseParameters(methodStr, Arrays.asList(input)), true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign precompiled contract, " - + "with correct hash bytes") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters( - "validatemultisign(address,uint256,bytes32,bytes[])", argsStr); - - String methodStr = "testMultiPrecompileContract(bytes)"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, - AbiUtil.parseParameters(methodStr, Arrays.asList(input)), true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java deleted file mode 100644 index 548ebf5330b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java +++ /dev/null @@ -1,326 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VerifyBurnProof001 { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testPriKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testPriKey001); - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 1000_000_000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy VerfyMintProof contract ") - public void verifyBurnProof001() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testAddress001, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testPriKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/VerifyBurnProof001.sol"; - String contractName = "VerifyBurnProof001Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, testPriKey001, - testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "data length != 512") - public void verifyBurnProofTest002() { - - String argsStr = "\"" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a" - /// add more 32bytes - + "0000000000000000000000000000000000000000000000000000000000000064\""; - - //argsStr = argsStr + "0000000000000000000000000000000000000000000000000000000000000064"; - - String methedStr = "VerifyBurnProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "data is empty") - public void verifyBurnProofTest003() { - - String methedStr = "VerifyBurnProofSize003()"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, "", false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "value greate than Long.MAX_VALUE") - public void verifyBurnProofTest004() { - - //String methedStr = "VerifyBurnProofSize002(bytes)"; - String methedStr = "VerifyBurnProofSize001(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32)"; - String argsStr = "" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000fffffffffffffff" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - // parseLong will return Long.MAX_VALUE and checkResult false - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "verify success with address call") - public void verifyBurnProofTest005() { - String argsStr = "\"" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a" - + "\""; - - String methedStr = "VerifyBurnProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); - } - - @Test(enabled = true, description = "verify success with fuction call") - public void verifyBurnProofTest006() { - String argsStr = "" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a"; - - String methedStr = "VerifyBurnProofSize001(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java deleted file mode 100644 index a0c0df953e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java +++ /dev/null @@ -1,457 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VerifyMintProof001 { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testPriKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testPriKey001); - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 1000_000_000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy VerfyMintProof contract ") - public void verifyMintProofTest001() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testAddress001, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testPriKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/VerifyMintProof001.sol"; - String contractName = "VerifyMintProof001Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, testPriKey001, - testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "data length != 1504") - public void verifyMintProofTest002() { - - String argsStr = "\"" - + "a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000" - // add more bytes32 - + "0000000000000000000000000000000000000000000000000000000000000064" - + "\""; - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "data is empty") - public void verifyMintProofTest003() { - String methedStr = "VerifyMintProofSize003()"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, "", false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - } - - @Test(enabled = true, description = "leafCount greate than 2^32-1") - public void verifyMintProofTest004() { - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String argsStr = "\"" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "000000000000000000000000000000000000000000000000000000000000000a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "0000000000000000000000000000000000000000000000000000000100000002" - + "\""; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "verify success with address call") - public void verifyMintProofTest005() { - String argsStr = - "\"a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000\""; - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000060" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "39e261b362110781a20878cc19f480cb50df5e6b896ed9a1fea8b8a9a4239a17", contractResult); - - } - - @Test(enabled = true, description = "verify success with fuction call") - public void verifyMintProofTest006() { - String argsStr = - "a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000"; - - String methedStr = - "VerifyMintProofSize001(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertTrue(contractResult.length() > 1000); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java deleted file mode 100644 index 9ea86709e2e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java +++ /dev/null @@ -1,166 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class pedersenHash001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/pedersenHash001.sol"; - String contractName = "pedersenHashTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "data is empty") - public void test01DataIsEmpty() { - String method = "test1()"; - txid = PublicMethed - .triggerContract(contractAddress, method, "", false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - byte[] result = infoById.get().getContractResult(0).toByteArray(); - String boolResult = ByteArray.toHexString(ByteArray.subArray(result, 0, 32)); - System.out.println("boolResult: " + boolResult); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - boolResult); - - } - - @Test(enabled = true, description = "data length limit") - public void test02DataLengthLimit() { - String method = "test2(bytes)"; - // length:64 - String argsStr1 = "\"0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002\""; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - int boolResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertFalse(Boolean.valueOf(String.valueOf(boolResult))); - Assert.assertTrue(maxFeeLimit > infoById.get().getFee()); - - // length:128 - String argsStr2 = "\"0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr2, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "7d6b910840eb7b47f76492aca4a3344888b8fa5aab77a49e9445cda718d75040", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "normal") - public void test02Normal() { - String method = "test3(uint32,bytes32,bytes32)"; - String argsStr1 = "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002"; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("7d6b910840eb7b47f76492aca4a3344888b8fa5aab77a49e9445cda718d75040", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(testNetAccountAddress, balance - 1000000, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java deleted file mode 100644 index 26f29e5f69d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java +++ /dev/null @@ -1,476 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; - -@Slf4j -public class pedersenHash002 { - - public final String foundationAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - public static final String zenTrc20TokenOwnerKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTrc20TokenOwnerKey"); - public static final byte[] zenTrc20TokenOwnerAddress = PublicMethed - .getFinalAddress(zenTrc20TokenOwnerKey); - public static final String zenTrc20TokenOwnerAddressString = PublicMethed - .getAddressString(zenTrc20TokenOwnerKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - public ByteString contractAddressByteString; - public static byte[] contractAddressByte; - public static String contractAddress; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployShieldTrc20Txid; - public static String deployShieldTxid; - private BigInteger publicFromAmount; - Optional receiverShieldAddressInfo; - List shieldOutList = new ArrayList<>(); - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Deploy shield trc20 depend contract") - public void deployShieldTrc20DependContract() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(contractExcAddress, 10000000000000L, - foundationAccountAddress, foundationAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployShieldTrc20Txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTrc20Txid); - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - contractAddressByteString = infoById.get().getContractAddress(); - contractAddressByte = infoById.get().getContractAddress().toByteArray(); - contractAddress = Base58.encode58Check(contractAddressByte); - logger.info(contractAddress); - String filePath = "src/test/resources/soliditycode/pedersenHash002.sol"; - contractName = "TokenTRC20"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - data = "\"" + contractAddress + "\"" + "," + scalingFactorLogarithm; - constructorStr = "constructor(address,uint256)"; - deployShieldTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTxid); - infoById = PublicMethed.getTransactionInfoById(deployShieldTxid, blockingStubFull); - shieldAddressByteString = infoById.get().getContractAddress(); - shieldAddressByte = infoById.get().getContractAddress().toByteArray(); - shieldAddress = Base58.encode58Check(shieldAddressByte); - logger.info(shieldAddress); - - data = "\"" + shieldAddress + "\"" + "," + totalSupply.toString(); - String txid = PublicMethed.triggerContract(contractAddressByte, - "approve(address,uint256)", data, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("approve:" + txid); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - publicFromAmount = getRandomAmount(); - } - - - @Test(enabled = true, description = "left and right value is 0") - public void test01LeftAndRightValueIsZero() throws Exception { - //Query account before mint balance - final Long beforeMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Generate new shiled account and set note memo - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters("ByValueIsZero", publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - } - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20Parameters(String methodSuffix, - BigInteger publicFromAmount, GrpcAPI.DecryptNotesTRC20 inputNoteList, - List shieldedAddressInfoList, List outputNoteList, - String publicToAddress, Long pubicToAmount, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20Parameters.Builder builder - = GrpcAPI.PrivateShieldedTRC20Parameters.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - long valueBalance = 0; - - if (inputNoteList != null) { - logger.info("Enter transfer type code"); - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(methodSuffix, position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String shieldedAddress = inputNoteList.getNoteTxs(i).getNote().getPaymentAddress(); - - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(0).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - //ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(esk.get().getAsk()); - builder.setNsk(esk.get().getNsk()); - builder.setOvk(esk.get().getOvk()); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(0).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTRC20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTRC20NoteBuilder.setNote(noteBuild.build()); - spendTRC20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTRC20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTRC20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTRC20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - valueBalance = Math - .addExact(valueBalance, inputNoteList.getNoteTxs(i).getNote().getValue()); - builder.addShieldedSpends(spendTRC20NoteBuilder.build()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - try { - return blockingStubFull.createShieldedContractParameters(builder.build()); - } catch (Exception e) { - Status status = Status.fromThrowable(e); - System.out.println("createShieldedContractParameters failed,error " - + status.getDescription()); - } - return null; - } - - public String getRootAndPath(String methodSuffix, long position, - WalletSolidityGrpc.WalletSolidityBlockingStub - blockingStubSolidity) { - String methodStr = "getPath" + methodSuffix + "(uint256)"; - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - argsStr = "000000000000000000000000000000000000000000000000" + argsStr; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(shieldAddressByte, methodStr, argsStr, true, - 0, 1000000000L, "0", 0, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubSolidity); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - return ByteArray.toHexString(result); - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public Optional getNewShieldedAddress(WalletGrpc.WalletBlockingStub - blockingStubFull) { - ShieldedAddressInfo addressInfo = new ShieldedAddressInfo(); - - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - final Optional d = Optional.of(blockingStubFull.getDiversifier( - EmptyMessage.newBuilder().build())); - - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.get().getAsk()); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(askBuilder.build())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.get().getNsk()); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nskBuilder.build())); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - Optional ivk = Optional.of(blockingStubFull - .getIncomingViewingKey(viewBuilder.build())); - - GrpcAPI.IncomingViewingKeyDiversifierMessage.Builder builder - = GrpcAPI.IncomingViewingKeyDiversifierMessage - .newBuilder(); - builder.setD(d.get()); - builder.setIvk(ivk.get()); - Optional addressMessage = Optional.of(blockingStubFull - .getZenPaymentAddress(builder.build())); - addressInfo.setSk(sk.get().getValue().toByteArray()); - addressInfo.setD(new DiversifierT(d.get().getD().toByteArray())); - addressInfo.setIvk(ivk.get().getIvk().toByteArray()); - addressInfo.setOvk(expandedSpendingKeyMessage.get().getOvk().toByteArray()); - addressInfo.setPkD(addressMessage.get().getPkD().toByteArray()); - - return Optional.of(addressInfo); - - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** - * constructor. - */ - public static List addShieldTrc20OutputList(List shieldOutList, - String shieldToAddress, String toAmountString, String menoString, - WalletGrpc.WalletBlockingStub blockingStubFull) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - //noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - noteBuild.setRcm(ByteString.copyFrom(blockingStubFull.getRcm(EmptyMessage.newBuilder().build()) - .getValue().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - /** - * constructor. - */ - public Long getBalanceOfShieldTrc20(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return Long.parseLong(hexBalance, 16); - } - - /** - * constructor. - */ - public byte[] getRandomOvk() { - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - return expandedSpendingKeyMessage.get().getOvk().toByteArray(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * constructor. - */ - public BigInteger getRandomAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return BigInteger.valueOf(x); - } - - public byte[] longTo32Bytes(long value) { - byte[] longBytes = ByteArray.fromLong(value); - byte[] zeroBytes = new byte[24]; - return ByteUtil.merge(zeroBytes, longBytes); - } - - - /** - * constructor. - */ - public static String getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getString("value"); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java deleted file mode 100644 index 82c01e7316a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java +++ /dev/null @@ -1,802 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class verifyTransferProof001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/verifyTransferProof001.sol"; - String contractName = "verifyTransferProofTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "data is empty") - public void test01DataIsEmpty() { - String method = "test1()"; - txid = PublicMethed - .triggerContract(contractAddress, method, "", false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "data length limit") - public void test02DataLengthLimit() { - String method = "test2(bytes)"; - Optional infoById = null; - // length:2048 - String argsStr1 = "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - // length:2784 - String argsStr2 = "\"0000000000000000000000000000000000000000000000000000000000000520" - + "00000000000000000000000000000000000000000000000000000000000007c0" - + "0000000000000000000000000000000000000000000000000000000000000860" - + "898bb618ff2874a2b706e000d663c8e7ff7095ca404e131ce712583d7a3bf717" - + "b7b6ec3705a0823d09524e13c81bd4f44e6c796e63b197ffcdb6ec7bb44ff505" - + "2487fbd8a96638187266aa9c54795e0c14aabcd72d45b6d13ba304b539cbc7ed" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "82f70d55b1d9131cd3d41b7491636291a5ac41ed3372e4fe502d1c4a911cce4b" - + "49c6eaf2968c27437831622072b8f8cfa18791084189e7c4764c104a360bbe70" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "7c62133e78f43c71c49e8b85b145377c51c7d4dfd7c44656d62363144f243575" - + "1f2b46d412955c11a51cd81f6499bd0e9cf9c5a3fa12befe26b1e992e41cfd4c" - + "f1243c6008688639d9dffa4670b74546f66be60209a9c5664a9de7dcca856f6a" - + "fdfb2e8cf0083a20dbf2899042baa469949f7993f7b0f3606d70f443486ebf46" - + "9232a4e7a899e52a7479d9ca981ee7fe96250e4ef8d6899d89e8c33be62ac65c" - + "a97e4cd3d9a58033d35f9a7c45375f0b8866db6db15fcbd185e6c254cd0300b9" - + "364a3c2d9499e474bf207ce2f2b67427df0796d2c221efb28b7fccea210b58ba" - + "01f5a9b4a12eb295ab0fecbe97f01bf4841002e94e1334a513755403f6832ce3" - + "0ab328b11e8772aa922dc7c84768c887b38b35e39df177e3fc4f760051209e1a" - + "9dfef66affba94f21d5a28c39a893419af506faee2217f0c605830427173a7d5" - + "521c7b5bf3ff99421c69c861af0fc30b565332ff1aad344afd9dd7b40e3da769" - + "67ecbac59d221641a28b19134e599c1d20c5cc55ac45217a68b0b9106872b92a" - + "8d55ca2e65e84ccd45a21d88a0eec096d98525d7e6751d4dbc4ddcb6aaec334b" - + "c7061b48ba27b89f193ad9e9f4d9c98aa1316b08f018222a3d92c1da7e8b7611" - + "806764eeb09ac490eea1f01d16ba8378e0c64396a0c06a707ed6027eae76938e" - + "74fa404d1ed9a955c7fe85eabc07b76eb58287d749a8dd304e810f94f680120b" - + "6e792117717f8b5b7f9f01416205900d962ffb69540e85562688604c26db4987" - + "0de0658d072aeb649809bf6f21714975f87e75df545e583c77bd6f786b3cc5c6" - + "08051b7885a732ac9bd49271d7ae9caea7d995d2ce5b18740f2b5b0de32d1337" - + "46f30ae9eb6d1f54ea1e4e228b6a22849a99f0a2decd09c806d8bd7cad6810de" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "c68b0fa0e76ffae969421ef87a0e27e4ad5a94b5bf2b5237c0a0e57259f20e60" - + "60525cfbc22ff838b067110121840a6885bff4516a5dc21eedce04f79b04b403" - + "10e640233b876885329599a78ce1cdc5dff83a29216f7fe58f225338963ec9b4" - + "9811e7479ef258776289394525c1070b70d3aeacb6d9d4a9065024ca21d8ed08" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "73238d94e2ad7575eb6067b1e5889a8445ef29dc377bdba0807f716b0b75b13e" - + "00ef0b6303b098a8af5e2deb8d506aaa710a58805325aa2097c19a63b876e5b4" - + "26e055e92683f24fab7c79b7d8825928fc3dc356d496c09069b8fd0d01df275b" - + "b0a57952d3adc1f31570d3626d2011a725f9caaf857e253b4e4791adfb7babe7" - + "27c0b4791f16050dfdb1a4763f75fd0f970ca19ee66c36462e43dff2899c5d62" - + "3e363389f3dedb855c09e051f20f3f27ee52d2d267ae1f1bf024c2f63068b682" - + "0b578b39aebb57b8fc055a7d13d25574dfcde58656beec84dde4ba439b0bbb5d" - + "0b5b24a2cf71f6b68b56c5ef1bac89888b5b6827bca8cd8b47fc394cf89a6c23" - + "468f7857b566cddf39f06eed6ac079f20044b42381fb0ca969c4f425ed04e166" - + "09e582987c6af094c8afbfeb52e14b0e4e342c82dc784405631f4a985c826e51" - + "4a9b50b6ad41db1a403b0ced0f5f1e4a9ae2964237b6874056c8044233b331e1" - + "a8bcf84d0584c12dc42ebd27cca972b31c475a644450afcfd40c36c739740566" - + "8b377c8ed99dcca1a5ec03ca990d6c4cb846ad561dd204c66c834fc024030b75" - + "106bdca9e57e8d68d19e4183a349bc488b9c3d666f59f9bdca8e92457dbbacf5" - + "1a0e074d5cb64b54e533aef3d1da2b673b7a87cae612c7faed50563a20970a9b" - + "07539d7ea4d57a83defeaefa024832fe6ec1db4c3a4ef6badcc4d95e0d22f4ec" - + "e4f272a22dcfaa2326bc301f2dfac22fa35bd0c9a40262caf424e2e62b3e0a45" - + "c2fa591c482e923a2d6b3c4ba0819df430f4d548105071f7cb561749459f15d2" - + "c2fa591c482e923a2d6b3c4ba0819df430f4d548105071f7cb561749459f15d2\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr2, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "tree width limit") - public void test03TreeWidthLimit() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000ffffffff" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "spend count greater than 2") - public void test04SpendCountGreaterThan2() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000521" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "e5ae9d43a82fc3bc74272dbe20dcf99d2d37ff4ae1689c3f9b53d40113cf5fa8" - + "77e4f78bef9e692985e3a7cd08b92a8380aa0aaec623b7cf3aae5c5a13b41602" - + "9b40cc7690e15b1437f1d88aaf3b44649e23cbd4013b4b41da1efdf31b774779" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "22389ba23e8f871b2a2e71d87c67f03eaace9849e59e8cfd54d5ca783c9b8923" - + "2108740b5326d2802e5a09a263a2668f987425af3f76d61a5d3fa98896ea2a52" - + "db286eec8ac754634b2e099f661b194b79d99c4fc33f9eef975b1b2862f72866" - + "60b225e4f8a010864d82e87cbec9d1fab63a6ae57f04a03f0ced73fb7ba73a71" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000d" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "fa05291a6d8af85cf9dc46f04687c31c12a4de8b2e9b51a55f2b777fb0220ddb" - + "c11bbb1f5025494923823c12fe864d290958384d5bc5e4d920e2bd9db70d005b" - + "b609c343bf7a9b3275ef9419ec1c5dfca574b9e17d67a782b745d2a4c830346d" - + "c77bfd763dfab3fa57596693a828cba2dbbd43fa0daa454136cd61f303e66d72" - + "b91efc162b5a4474b71f9b688af8513bc0e19fbcc834223c02c942f504c4286a" - + "359462bc8993d7b41aead7ac25a25c64b5ae662cea2370ff912e2b2a6ef76bbe" - + "f5ae2a40d920ee79197c99b9ba92df929d445bbd4a0384ce3e637d59939086dc" - + "06042ef2abbb6ea7a599acac186d8fce957c1632d1dc64c9cc04a4a597d42923" - + "491440cfa5bf9c0d387ef77902921343929900044165384c73b30b38c466e4f6" - + "d71f6c1e1b6af43ce2ec0572cd3a28e7c1d5caab600cb001effd07e4182e89be" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "3f153ababa83e18ff39b3149b893d90aebd440521b670b10e8268f7a98f42f06" - + "64efcf611c6c0e11f9edfeca53af7e8fc758f92b713fb4c104df4f6868eb6807" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "4fd0c6e8ed03c4e7797c4da435e5da8b7ecf63c765c8f5817fe29aa4f54e6057" - + "fc5dda67c0109f8ce48344c9c55fb8081a79ad549bd7d162b3f334a9219f8169" - + "a2f5c0f129ac81ab9f93b13a09ec25b40356420dbfe9aa21d367af61415a6a45" - + "82b5efd3f827c7ca99371b1a029e1781156f068e000fdb26ea1b078ce24ae4e1" - + "571001515de0d6d55d2eb7ed4371397b993b2fe4df3addd53248e3adfc24c6fe" - + "81e7b3679ba49fb7e5ef8c13661e7d442210cac48e93398f6d731b3770fcb23e" - + "01c0d34d139df0c31c1dbdf8b08fe0d6029845b1abc990986408191905d04e76" - + "44dd0fc25446d753e94638ee48bb5e088f4483ce9e648093e654ba762ea516df" - + "5bb29cb95cfe347fc2f109ff86d5596bdb89c116b4805b9c6bdc019049b597f3" - + "ee52b22ececc9c7bc4d2c4dd61f9e16bc9feb07a5575f28e577a2d67c1eb3d24" - + "d6583d39f9ea3fe2de10132de6303217cca345201a194ecde8ad098f49d3f63b" - + "2f1f12c99a24d5779e7b4d1e6aa4fc3e1f0bd671701f42e43f3530501e7e2c00" - + "b47f9f2c332b75a849eb94a260a9d2a846212562ec57e927e071962ddc5dda5c" - + "dd9d38d346666659216b4897492ee991b359f9d3adf8bb576720f3b1d49be957" - + "a5c39e894b98bea2538645b434d47e4e7c71fdf765aeae264dd916ff41542eee" - + "063bbed2ff1e40ee1a2a949d5bd197e5936709cdb68151108221b8478fa15d86" - + "d8aff952d21265677a1a363cf7f492de8c0715cb95960d149842e3cee99bdb32\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "duplicate nullifiers") - public void test05DuplicateNullifiers() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "00000000000000000000000000000000000000000000000000000000000007c0" - + "0000000000000000000000000000000000000000000000000000000000000860" - + "f95c0de8b0b573b6a302be34f42cab92fb84ad87be4c9e7c5016ccf4e5692552" - + "79279550d90ed369e0c60b07bc0ace565391941aff977ea101b221c26c14490d" - + "43b5d1b2f29511ff3425e353eb022493f3771203daff96e326477afbe34f7357" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0d9a42f99c055f6218415145bdd3b18496273ccd579c9370cbb312505e65ac2f" - + "88a987bdf381b7a6c41f5683334f9becdec01ab10fa4976a9b15191b9e33fc5c" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0a43f2568d0aca1a589ff1b76a5147123e1b2c76634970378d742088d68187d7" - + "ed942fe6a584633ab56c66b5824fa24e1380d371abf8aedbcae1b45927fcc236" - + "216f0eafbbdee5f09a136f5dedd86ac5a1ebe7317942bc1999cd0b0b1c11b707" - + "295f566ff309ea8510919d2507b558d7f88151746aab05866a8708d1d70acf42" - + "80f40957fe79d81223cbe9f4eef86be1d4ab19fd3f26f6e08aa27477a8b2160f" - + "44de6d5ce257eccdf91ab3de59461420b20ee95a75bd031f117796e9d1995e85" - + "0c8900a176dd7fc60694716ef82d6ba5d72698f5580503575cecf09a912574d0" - + "02d9761fef0f283242404cbadaa10a70270dae33899c626f27cc626e2c7737d7" - + "5cf62af8190938d92f04d9cb4fcab07d98482843c9b062d5a3c48b1d6259f94c" - + "fa6961c578ecd8b87052edd19b7dc9fa168349cc125ed8e9beddb04450e0558b" - + "0a43f2568d0aca1a589ff1b76a5147123e1b2c76634970378d742088d68187d7" - + "ad182389453f849cf316d7d8c1c8b0da2675c404d09a8a7efb6ab4f81e5d253e" - + "2ab630a209d6dbd4446cc274859a4a97175cac7fc9d20544f5df8d5e6cc37856" - + "a305d5f20688846a81e57dd6141049691495e48ad37cf38183408b4e7ff9a250" - + "b449788c9ef60787fa698915b959979713e800c36966dc737032ab5455374854" - + "e31eebc49b73fc73e709962c69da79e4a3eb55c7311d245e671c83213562da8f" - + "751483514e1c9fead10186b95783a29b880f1c443fcb0c12fad1c8f4f1f1f8b2" - + "10792470322970e28ff0f1cff37531a594a164a4af755fa0d7bb9f24c2d4d7df" - + "2ebe0ff20d7a8a01bbc19ea13f92fe1ea3a8676cdb81efaee30ed4a0e15de0e4" - + "7ce1f4304ad9b824b08f26d655c2c04cdb1e1bf69f8796d5360af32193cceb26" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "36ecefb9a2264d4515ef9c1dc23bd8de87930c2434c3426df4b12afc17ccde46" - + "8e6a99a43572ea6c6110db239cd60627e927d339dfad1920bb88ce2335d91e07" - + "eb6968339a770e46c2c7acbedfdcf93678493f2d3ea03c4a78a2f28925e0e5b4" - + "632d959daaa129e79901713f5b8e3a233219371473b5c8f494dc28bceb399508" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "14c1d485df7f471413cf90be5bae3909ccb5812fbee683f91e1fc5b7178d8852" - + "51a559f6632e3beb24ed1e781de05d6fbb2a4600dd9b2195cdf378a18e2a31ed" - + "49936339e06e29754fe00956cde97338c627806596d681de95db6653d110a7a3" - + "95617c958e1c4d81d4baa99b295bddd6c3da2d4fb9dddc886d31461224ed423a" - + "68c4b504cbed65a19a43efe8c7f721cc9406d8251ca03bbdc6217f6f02077b45" - + "02a1db7de8fab00edc14df913fd7369c4e28294086bd2cb86bd1559133f211b6" - + "1382886e7feb401fdb9fc6ac186dd133d456a7a220615bb410ad79da8b0fb7b7" - + "c404341cf42246820f2afb70466b08658d55b24d3a53707ed88b82827e1358d0" - + "2fe7e8c746f6f7124d2dd3d1717d2859e8390f8f76147e1c767831924058ce70\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "duplicate output note") - public void test06DuplicateOutputNote() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "9144cda061b41702bbf641dc3864fa94bc934511895058f01b7bfbdbdb301f8c" - + "d43a44ccd4b131e6b37bd673f8ac6e554eb5b4ab599b6d2b66bc294b7767f506" - + "24614ac147e95287ff8351ed22aa43f2b3e82460dc79b57952e8a39bf4027c47" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "73792777f50b3c5cf7fcf88c7d24baf975c0b4132f2affa898df03874b3e8163" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "92a3ddb4b05a3903fd1d9693e047c7136ac048fd12a7384bfd569e57a265b1f9" - + "2e96a076fcd5722ff4e04bc31cec8aeb2fa5ee3006104a3046c28c4a1584293f" - + "d02e3f11e3ca072628d2fa4755699958223e3467ef7c2039ff699fd9616a5921" - + "0624e9ba16fc55a77d6d872854c638a1c3b6570267130cb43770661793fa9fda" - + "9406c39d8388060ece340e133238f9452e990d1adcc2a91a0bfe46403489043b" - + "51ac2c88e5f0f4fe74b65eb30ec50400a5334a59f3f7f425073edf66bc3ca8cf" - + "f599d1f6742d1ebf0e40dce32d81a4a5cafb1c0ec078a692b95c97265cce277c" - + "11bf7216ff5df3d0d916359abe8b1a5dedf30e5bd5ccf24e6659adc9a4db9558" - + "6369477f2a15447a56249fa1703f31b7b3800aff0cf67772d132bd74cf888ee5" - + "4f45236c6687ac59c89a6157e001bd5190fadba40d515f739636a7dbd77b5108" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "59eca5d4562a891db660355de4de8c14afa64332a8c58afc44108798fc070cba" - + "e90d708016a0f09278a895325c538a0773a011aa9f132dce77e073f39b864606" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "23540e10b3989fc8efdcadda1bcb840cce8580b45718082d5ace9fc4a6f4d45b" - + "d3ad992cbf4a32ece6a7911992c82b94a54705f7fbe680b5250c9b05cb1a31ca" - + "0d26babfd7f9614d5b3cbe84c7006f4aebcea2977d31c9761c5f7ef9c4b0a8eb" - + "98c35f51cd4ed7eef014a56ae50b4efb6555d497991ff7b282183d82f19282d5" - + "5ce8b8f286f6bdeae73981db2a615c7cb9c4fdaa7618502480945647aa1e98eb" - + "4dab59853f9bb3327f7ecbfd92fde4e2f49968562b468ca060447f1036172075" - + "163840bd0f1dca2495392228e23bf49b0934e14a145be29a9e42fb8477925c9f" - + "5a18093e51748a2494ee9191e16511bbae6d8c71d188c46286dd6dc5213b1d7f" - + "95eab6bade1ee763656b06c95d8e907dd8f3310722024cb9322d17724757f686" - + "23540e10b3989fc8efdcadda1bcb840cce8580b45718082d5ace9fc4a6f4d45b" - + "77b1609896bde81495ab555869c6ddbc5c7aac7274830f505486682093284fb6" - + "6f4aeab08e6417ab85026d97aeedfa26407b867227639653ec7a2fb529eb3e9f" - + "a207cb75c8eeb1c77fc3fc9949fc9c95e4b98806a9c6d7558f1f4e8f2a87df47" - + "375dc915db5332f6abbd87967796875ea8922e70e9ba135cdeabd171273884a9" - + "107992ee1a521f648c499620299a45031821e0639abadeec464a3ec3f439a823" - + "15bfe031aaaba0e3bc80fc359d7c7722e448e1e671447c41592cc0f27d35e1bc" - + "b5a4dd42ac75418f70f1a23f0de47fb6a2985ff86958816e52067612df232aa6" - + "9b5cedeab709b800eacc4b2d81582e4bb4f0a0e51571a5b03816126b39e1c9ab\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "checkResult is false") - public void test07CheckResultIsFalse() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c86b6ef8ac86" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "normal") - public void test08Normal() { - String method = "test3(bytes32[10][],bytes32[2][],bytes32[9][]" - + ",bytes32[2],bytes32,uint64,bytes32[33],uint256)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864", - true, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()).length() > 10000); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(testNetAccountAddress, balance - 1000000, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java deleted file mode 100644 index 4e5a7908092..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java +++ /dev/null @@ -1,262 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 8 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - @BeforeSuite - public void beforeSuite() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info("enter this"); - if (PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getCreateTime() == 0) { - PublicMethed.sendcoin(foundationZenTokenAddress, 20480000000000L, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 15000000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - PublicMethed.createAssetIssue(foundationZenTokenAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - } - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Public to shield transaction") - public void test1Public2ShieldTransaction() { - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Long afterNetUsed = PublicMethed.getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertTrue(receiverShieldTokenAmount == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, description = "Shield to public transaction") - public void test2Shield2PublicTransaction() { - note = notes.getNoteTxs(0).getNote(); - SpendResult result = PublicMethed.getSpendResult(shieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull); - Assert.assertTrue(!result.getResult()); - - shieldOutList.clear(); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue() - zenTokenFee, - zenTokenOwnerKey, blockingStubFull)); - - //When you want to send shield coin to public account,you should add one zero output amount cm - /* shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue() - zenTokenFee, - zenTokenOwnerKey, blockingStubFull));*/ - - PublicMethed.waitProduceNextBlock(blockingStubFull); - result = PublicMethed.getSpendResult(shieldAddressInfo.get(), notes.getNoteTxs(0), - blockingStubFull); - Assert.assertTrue(result.getResult()); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == note.getValue() - zenTokenFee); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance :" + afterAssetBalance); - } - - - @Test(enabled = false, - description = "Output amount can't be zero or below zero") - public void test3Shield2PublicAmountIsZero() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - memo = "Shield to public amount is zero"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (note.getValue() - zenTokenFee - (zenTokenFee - note.getValue())), memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, zenTokenFee - note.getValue(), - zenTokenOwnerKey, blockingStubFull)); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (note.getValue() - zenTokenFee), memo); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, 0, - zenTokenOwnerKey, blockingStubFull)); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (-zenTokenFee), memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue(), - zenTokenOwnerKey, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java deleted file mode 100644 index 6b761422c5b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java +++ /dev/null @@ -1,403 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken002 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - IncrementalMerkleVoucherInfo firstMerkleVoucherInfo; - IncrementalMerkleVoucherInfo secondMerkleVoucherInfo; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidity1 = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - } - - @Test(enabled = false, description = "Get merkle tree voucher info") - public void test01GetMerkleTreeVoucherInfo() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - firstMerkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - } - - - @Test(enabled = false, description = "Shield to shield transaction") - public void test02Shield2ShieldTransaction() { - receiverShieldAddressInfo = PublicMethed.generateShieldAddress(); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - ; - memo = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - receiverNote = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note:" + receiverNote.toString()); - Assert.assertTrue(receiverNote.getValue() == sendNote.getValue() - zenTokenFee); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on FullNode") - public void test03ScanNoteByIvkAndOvk() { - //Scan sender note by ovk equals scan receiver note by ivk on FullNode - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvk(receiverShieldAddressInfo, blockingStubFull).getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvk(sendShieldAddressInfo, blockingStubFull).getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on solidity") - public void test04ScanNoteByIvkAndOvkOnSolidityServer() { - - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on Pbft") - public void test05ScanNoteByIvkAndOvkOnPbftServer() { - - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on solidity") - public void test06ScanNoteByIvkAndOvkOnSolidityServer() { - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity1); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity1) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubSolidity1) - - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on solidity") - public void test07QueryNoteIsSpendOnSolidity() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubSolidity).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubSolidity1).getResult()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on PBFT") - public void test08QueryNoteIsSpendOnPbft() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubPbft).getResult()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query note and spend status on fullnode and solidity") - public void test09QueryNoteAndSpendStatusOnFullnode() { - Assert.assertFalse( - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getIsSpend()); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk, - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getNote()); - - Assert.assertFalse(PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getIsSpend()); - scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk, PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote()); - Assert.assertEquals(scanNoteByIvk, PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote()); - - shieldOutList.clear(); - memo = "Query note and spend status on fullnode " + System.currentTimeMillis(); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (notes.getNoteTxs(0).getNote().getValue() - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - receiverShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - Assert.assertTrue( - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getIsSpend()); - - Assert.assertTrue(PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getIsSpend()); - } - - @Test(enabled = false, description = "Get merkle tree voucher info") - public void test10GetMerkleTreeVoucherInfo() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - @Test(enabled = false, description = "Get merkle tree voucher info from Solidity") - public void test11GetMerkleTreeVoucherInfoFromSolidity() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubSolidity - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - @Test(enabled = false, description = "Get merkle tree voucher info from Pbft") - public void test12GetMerkleTreeVoucherInfoFromPbft() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubPbft - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java deleted file mode 100644 index 4480df80b5d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java +++ /dev/null @@ -1,474 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long costTokenAmount = 20 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, - description = "Public to two shield transaction") - public void test1Public2ShieldTransaction() { - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - @Test(enabled = false, - description = "Public to one public and one shield transaction") - public void test2Public2OneShieldAndOnePublicTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - final Long beforeBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - //When receiver public address don't active,the fee is 1000000 - Long sendToPublicAddressAmount = costTokenAmount - - sendToShiledAddress1Amount - zenTokenWhenCreateNewAddress; - logger.info("costTokenAmount " + costTokenAmount); - logger.info("sendToShiledAddress1Amount " + sendToShiledAddress1Amount); - logger.info("sendToPublicAddressAmount " + sendToPublicAddressAmount); - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - logger.info("txid:" + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenWhenCreateNewAddress); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - final Long afterBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - Assert.assertTrue(beforeBalance - afterBalance == 0); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to one public and two shield transaction") - public void test3Public2OneShieldAndOnePublicTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - final Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - final Long beforeReceiverPublicAssetBalance = PublicMethed - .getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertTrue(afterReceiverPublicAssetBalance - - beforeReceiverPublicAssetBalance == sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to one smart contract and one shield transaction") - public void test4Public2OneShieldAndOneSmartContractAddressTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - final Long beforeBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - String contractName = "tokenBalanceContract"; - String code = "608060405260ff806100126000396000f30060806040526" - + "004361060485763ffffffff7c010000000000000" - + "0000000000000000000000000000000000000000000600035041663a730416e8114604d578063b69ef8a8146" - + "081575b600080fd5b606f73ffffffffffffffffffffffffffffffffffffffff6004351660243560ab565b604" - + "08051918252519081900360200190f35b348015608c57600080fd5b50d38015609857600080fd5b50d280156" - + "0a457600080fd5b50606f60cd565b73ffffffffffffffffffffffffffffffffffffffff90911690d16000908" - + "15590565b600054815600a165627a7a723058202b6235122df66c062c2e723ad58a9fea93346f3bc19898971" - + "8f211aa1dbd2d7a0029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":" - + "[{\"name\":\"b\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":" - + "\"balance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, testKey002, fromAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - org.junit.Assert.assertTrue(smartContract.getAbi() != null); - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - contractAddress.toByteArray(), sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - logger.info("txid:" + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - final Long afterBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - Assert.assertTrue(beforeBalance - afterBalance == 0); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed - .getAssetIssueValue(contractAddress.toByteArray(), - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to two same shield address") - public void test5Public2TwoSameShieldAddress() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "First public to shield same address transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Second public to shield same address transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress2Amount, memo2); - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.getShieldNotesByIvk(shieldAddressInfo1, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 2); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - note = notes.getNoteTxs(1).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java deleted file mode 100644 index 6284508261e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java +++ /dev/null @@ -1,286 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Optional sendShieldAddressInfo; - String sendshieldAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Args.setFullNodeAllowShieldedTransaction(true); - Assert.assertTrue(PublicMethed.sendcoin(receiverPublicAddress, 1000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Shield to two shield transaction") - public void test1Shield2TwoShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - String memo1 = "Shield to shield address1 transaction"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - @Test(enabled = false, - description = "Shield to one public and one shield transaction") - public void test2Shield2OneShieldAndOnePublicTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Shield to one public and two shield transaction") - public void test3Public2OneShieldAndOnePublicTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = 4 * zenTokenFee; - final Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenWhenCreateNewAddress; - shieldOutList.clear(); - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - //When receiver public address don't active,the fee is 1000000 - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] notActivePublicAddress = ecKey3.getAddress(); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - notActivePublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - final Long afterNotActivePublicAssetBalance = PublicMethed - .getAssetIssueValue(notActivePublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - logger.info("afterNotActivePublicAssetBalance:" + afterNotActivePublicAssetBalance); - logger.info("sendToPublicAddressAmount:" + sendToPublicAddressAmount); - Assert.assertEquals(afterNotActivePublicAssetBalance, sendToPublicAddressAmount); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java deleted file mode 100644 index 23398284924..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java +++ /dev/null @@ -1,215 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(receiverPublicAddress, 1000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, - description = "The receiver shield address can't more then 2") - public void test1ReceiverShieldAddressCanNotMoreThenTwo() { - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - Optional shieldAddressInfo3 = PublicMethed.generateShieldAddress(); - String shieldAddress3 = shieldAddressInfo3.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - logger.info("shieldAddress3:" + shieldAddress3); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - Long sendToShiledAddress3Amount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - String memo3 = "Shield to shield address3 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress3, - "" + sendToShiledAddress3Amount, memo3); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, - description = "The receiver can't only one public address") - public void test2ReceiverPublicCanNotOnlyOnePublic() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - shieldOutList.clear(); - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, costTokenAmount - zenTokenFee, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, - description = "Public send amount must equal receiver amount + shieldFee") - public void test3SendAmountMustEqualReceiverAmountPlusShieldFee() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - //Public receiver amount is wrong - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount - 1, - zenTokenOwnerKey, blockingStubFull)); - - //Shield receiver amount is wrong - sendToShiledAddress1Amount = 1 * zenTokenFee; - sendToShiledAddress2Amount = 2 * zenTokenFee; - sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + (sendToShiledAddress1Amount - 1), memo1); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - - sendToShiledAddress1Amount = 1 * zenTokenFee; - sendToShiledAddress2Amount = 2 * zenTokenFee; - sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java deleted file mode 100644 index 7b01959b2cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java +++ /dev/null @@ -1,266 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, description = "Shield note memo is one char") - public void test1ShieldMemoIsOneChar() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //One char. - memo = "."; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, description = "Shield note memo is 512 char") - public void test2ShieldMemoIs512Char() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //512 char. - memo = "1234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "7812345678"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, description = "Shield note memo is 514 char") - public void test3ShieldMemoIs513Char() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //514 char. - memo = "-1234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "7812345678"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - logger.info(PublicMethed.getMemo(note)); - Assert.assertTrue(PublicMethed.getMemo(note).length() == 512); - Assert.assertEquals(PublicMethed.getMemo(note), memo.substring(0, 512)); - } - - @Test(enabled = false, description = "Shield note memo is empty") - public void test4ShieldMemoIsEmpty() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //Empty memo - memo = ""; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, 2 * zenTokenFee, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - //Shield send to it self - memo = ""; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), - PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull).getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - - @Test(enabled = false, description = "Shield note memo is empty") - public void test5ShieldMemoIsEmpty() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - memo = "{\n" - + " note {\n" - + " value: 49957\n" - + " payment_address: \"ztron1f42n7h0l3p8mlaq0d0rxdkhq" - + "n6xuq49xhvj593wfduy24kn3xrmxfpqt8lnmh9ysnu5nzt3zgzx\"\n" - + " rcm: \"\\210x\\256\\211\\256v\\0344\\267\\240\\375\\377xs\\3" - + "50\\3558^Y\\200i0$S\\312KK\\326l\\234J\\b\"\n" - + " memo: \"System.exit(1);\"\n" - + " }\n" - + " txid: \"\\215\\332\\304\\241\\362\\vbt\\250\\364\\353\\30" - + "7\\'o\\275\\313ya*)\\320>\\001\\262B%\\371\\'\\005w\\354\\200\"\n" - + "}"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, 2 * zenTokenFee, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java deleted file mode 100644 index f43924eedcc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java +++ /dev/null @@ -1,639 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DiversifierMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PaymentAddressMessage; -import org.tron.api.GrpcAPI.ViewingKeyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken007 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo1; - Optional sendShieldAddressInfo2; - Optional sendShieldAddressInfo3; - Optional receiverShieldAddressInfo; - String sendShieldAddress1; - String sendShieldAddress2; - String sendShieldAddress3; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo1; - String memo2; - String memo3; - Note sendNote1; - Note sendNote2; - Note sendNote3; - Note receiverNote1; - Note receiverNote2; - Note receiverNote3; - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress1 = ecKey1.getAddress(); - String zenTokenOwnerKey1 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress2 = ecKey2.getAddress(); - String zenTokenOwnerKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress3 = ecKey3.getAddress(); - String zenTokenOwnerKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress4 = ecKey4.getAddress(); - String zenTokenOwnerKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey1); - PublicMethed.printAddress(zenTokenOwnerKey2); - PublicMethed.printAddress(zenTokenOwnerKey3); - PublicMethed.printAddress(zenTokenOwnerKey4); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress1, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress2, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress3, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress4, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo1 = PublicMethed.generateShieldAddress(); - sendShieldAddressInfo2 = PublicMethed.generateShieldAddress(); - sendShieldAddressInfo3 = PublicMethed.generateShieldAddress(); - sendShieldAddress1 = sendShieldAddressInfo1.get().getAddress(); - sendShieldAddress2 = sendShieldAddressInfo2.get().getAddress(); - sendShieldAddress3 = sendShieldAddressInfo3.get().getAddress(); - logger.info("sendShieldAddressInfo1:" + sendShieldAddressInfo1); - logger.info("sendShieldAddressInfo2:" + sendShieldAddressInfo2); - logger.info("sendShieldAddressInfo3:" + sendShieldAddressInfo3); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - memo3 = "Shield memo3 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (sendTokenAmount - zenTokenFee), memo1); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress1, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey1, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (sendTokenAmount - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress2, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress3, - "" + (sendTokenAmount - zenTokenFee), memo3); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress3, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey3, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - sendNote1 = notes.getNoteTxs(0).getNote(); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo2, blockingStubFull); - sendNote2 = notes.getNoteTxs(0).getNote(); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo3, blockingStubFull); - sendNote3 = notes.getNoteTxs(0).getNote(); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get spending key") - public void test01GetSpendingKey() { - sk = blockingStubFull.getSpendingKey(EmptyMessage.newBuilder().build()); - logger.info("sk: " + ByteArray.toHexString(sk.getValue().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get diversifier") - public void test02GetDiversifier() { - diversifierMessage1 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d1: " + ByteArray.toHexString(diversifierMessage1.getD().toByteArray())); - diversifierMessage2 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d2: " + ByteArray.toHexString(diversifierMessage2.getD().toByteArray())); - diversifierMessage3 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d3: " + ByteArray.toHexString(diversifierMessage3.getD().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get expanded spending key") - public void test03GetExpandedSpendingKey() { - expandedSpendingKeyMessage = blockingStubFull.getExpandedSpendingKey(sk); - logger.info("ask: " + ByteArray.toHexString(expandedSpendingKeyMessage.getAsk().toByteArray())); - logger.info("nsk: " + ByteArray.toHexString(expandedSpendingKeyMessage.getNsk().toByteArray())); - logger.info("ovk: " + ByteArray.toHexString(expandedSpendingKeyMessage.getOvk().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get AK from ASK") - public void test04GetAkFromAsk() { - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.getAsk()); - ak = blockingStubFull.getAkFromAsk(askBuilder.build()); - logger.info("ak: " + ByteArray.toHexString(ak.getValue().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get Nk from Nsk") - public void test05GetNkFromNsk() { - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.getNsk()); - nk = blockingStubFull.getNkFromNsk(nskBuilder.build()); - logger.info("nk: " + ByteArray.toHexString(nk.getValue().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get incoming viewing Key") - public void test06GetIncomingViewingKey() { - ViewingKeyMessage.Builder viewBuilder = ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.getValue()); - viewBuilder.setNk(nk.getValue()); - ivk = blockingStubFull.getIncomingViewingKey(viewBuilder.build()); - logger.info("ivk: " + ByteArray.toHexString(ivk.getIvk().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get Zen Payment Address") - public void test07GetZenPaymentAddress() { - IncomingViewingKeyDiversifierMessage.Builder builder = - IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage1); - builder.setIvk(ivk); - PaymentAddressMessage addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd1: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address1: " + addressMessage.getPaymentAddress()); - addressInfo1.setSk(sk.getValue().toByteArray()); - addressInfo1.setD(new DiversifierT(diversifierMessage1.getD().toByteArray())); - addressInfo1.setIvk(ivk.getIvk().toByteArray()); - addressInfo1.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo1.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo1 = Optional.of(addressInfo1); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage2); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd2: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address2: " + addressMessage.getPaymentAddress()); - addressInfo2.setSk(sk.getValue().toByteArray()); - addressInfo2.setD(new DiversifierT(diversifierMessage2.getD().toByteArray())); - addressInfo2.setIvk(ivk.getIvk().toByteArray()); - addressInfo2.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo2.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo2 = Optional.of(addressInfo2); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage3); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd3: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address3: " + addressMessage.getPaymentAddress()); - addressInfo3.setSk(sk.getValue().toByteArray()); - addressInfo3.setD(new DiversifierT(diversifierMessage3.getD().toByteArray())); - addressInfo3.setIvk(ivk.getIvk().toByteArray()); - addressInfo3.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo3.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo3 = Optional.of(addressInfo3); - - - } - - @Test(enabled = false, description = "Shield to shield transaction") - public void test08Shield2ShieldTransaction() { - //S to S address1 - receiverShieldAddress1 = receiverAddressInfo1.get().getAddress(); - shieldOutList.clear(); - ; - memo1 = "Send shield to receiver1 shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress1, - "" + (sendNote1.getValue() - zenTokenFee), memo1); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - //S to S address2 - receiverShieldAddress2 = receiverAddressInfo2.get().getAddress(); - shieldOutList.clear(); - ; - memo2 = "Send shield2 to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress2, - "" + (sendNote2.getValue() - zenTokenFee), memo2); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo2, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo2.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - //S to S address3 - receiverShieldAddress3 = receiverAddressInfo3.get().getAddress(); - shieldOutList.clear(); - ; - memo3 = "Send shield3 to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress3, - "" + (sendNote3.getValue() - zenTokenFee), memo3); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo3, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo3.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey3, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Same sk and different d can produce different - // shield address,the notes can scan out by same ivk. - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo1, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - - receiverNote1 = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note1:" + receiverNote1.toString()); - Assert.assertTrue(receiverNote1.getValue() == sendNote1.getValue() - zenTokenFee); - receiverNote2 = notes.getNoteTxs(1).getNote(); - logger.info("Receiver note2:" + receiverNote2.toString()); - Assert.assertTrue(receiverNote2.getValue() == sendNote2.getValue() - zenTokenFee); - receiverNote3 = notes.getNoteTxs(2).getNote(); - logger.info("Receiver note3:" + receiverNote3.toString()); - Assert.assertTrue(receiverNote3.getValue() == sendNote3.getValue() - zenTokenFee); - } - - @Test(enabled = false, - description = "Shield to shield transaction without ask") - public void test09Shield2ShieldTransactionWithoutAsk() { - //Same sk and different d can produce different shield address, - // the notes can use by scan from same ovk. - sendShieldAddressInfo1 = PublicMethed.generateShieldAddress(); - sendShieldAddress1 = sendShieldAddressInfo1.get().getAddress(); - sendShieldAddressInfo2 = PublicMethed.generateShieldAddress(); - sendShieldAddress2 = sendShieldAddressInfo2.get().getAddress(); - sendShieldAddressInfo3 = PublicMethed.generateShieldAddress(); - sendShieldAddress3 = sendShieldAddressInfo3.get().getAddress(); - - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo3, blockingStubFull); - receiverNote1 = notes.getNoteTxs(0).getNote(); - receiverNote2 = notes.getNoteTxs(1).getNote(); - receiverNote3 = notes.getNoteTxs(2).getNote(); - shieldOutList.clear(); - ; - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - shieldOutList.clear(); - ; - memo2 = "Send shield address 2 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (receiverNote2.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo2.get(), notes.getNoteTxs(1), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - shieldOutList.clear(); - ; - memo3 = "Send shield address 3 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress3, - "" + (receiverNote3.getValue() - zenTokenFee), memo3); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - receiverAddressInfo3.get(), notes.getNoteTxs(2), - shieldOutList, - null, 0, - zenTokenOwnerKey3, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByOvk(receiverAddressInfo3, blockingStubFull); - logger.info("notes count:" + notes.getNoteTxsCount()); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - sendNote1 = notes.getNoteTxs(0).getNote(); - logger.info("Receiver1 note:" + sendNote1.toString()); - Assert.assertTrue(sendNote1.getValue() == receiverNote1.getValue() - zenTokenFee); - Assert.assertEquals(memo1, PublicMethed.getMemo(sendNote1)); - - sendNote2 = notes.getNoteTxs(1).getNote(); - logger.info("Receiver2 note:" + sendNote2.toString()); - Assert.assertTrue(sendNote2.getValue() == receiverNote2.getValue() - zenTokenFee); - Assert.assertEquals(memo2, PublicMethed.getMemo(sendNote2)); - - sendNote3 = notes.getNoteTxs(2).getNote(); - logger.info("Receiver3 note:" + sendNote3.toString()); - Assert.assertTrue(sendNote3.getValue() == receiverNote3.getValue() - zenTokenFee); - Assert.assertEquals(memo3, PublicMethed.getMemo(sendNote3)); - } - - @Test(enabled = false, description = "Get shield Nulltifier") - public void test10GetShieldNulltifier() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - Assert.assertEquals(PublicMethed.getShieldNullifier(sendShieldAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).length(), 64); - notes = PublicMethed.listShieldNote(receiverAddressInfo1, blockingStubFull); - Assert.assertEquals(PublicMethed.getShieldNullifier(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).length(), 64); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - } - - @Test(enabled = false, - description = "Same sk transfer shield address note is spent") - public void test11SameSkTransferShieldAddressNoteCanSpent() { - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - - receiverNote1 = notes.getNoteTxs(0).getNote(); - shieldOutList.clear(); - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - Assert.assertFalse(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - } - - @Test(enabled = false, description = "Same sk transfer two shield address," - + "in one transaction send to these shield transaction") - public void test12SameSkTransferTwoShieldAddressInOneTransaction() { - shieldOutList.clear(); - memo1 = "Send to first shield address " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress1, - "" + zenTokenFee, memo1); - memo2 = "Send to second shield address " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress2, - "" + (costTokenAmount - 2 * zenTokenFee), memo2); - logger.info("address1 receiver amount:" + zenTokenFee); - logger.info("address2 receiver amount:" + (costTokenAmount - 2 * zenTokenFee)); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - zenTokenOwnerAddress4, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey4, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 5); - Assert.assertTrue(notes.getNoteTxs(3).getNote().getValue() == zenTokenFee); - Assert.assertTrue(notes.getNoteTxs(4).getNote().getValue() - == (costTokenAmount - 2 * zenTokenFee)); - Assert.assertEquals(PublicMethed.getMemo(notes.getNoteTxs(3).getNote()), memo1); - Assert.assertEquals(PublicMethed.getMemo(notes.getNoteTxs(4).getNote()), memo2); - - shieldOutList.clear(); - ; - receiverNote1 = notes.getNoteTxs(3).getNote(); - receiverNote2 = notes.getNoteTxs(4).getNote(); - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(3), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - shieldOutList.clear(); - ; - memo2 = "Send shield address 2 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (receiverNote2.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo2.get(), notes.getNoteTxs(4), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo1, blockingStubFull); - sendNote1 = notes.getNoteTxs(0).getNote(); - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (sendNote1.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(3), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(4), blockingStubFull).getResult()); - - notes = PublicMethed.getShieldNotesByOvk(receiverAddressInfo1, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(3), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(4), blockingStubFull).getResult()); - - //Send shield coin without ask when there is no output shield address - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo2.get(), notes.getNoteTxs(1), - shieldOutList, - zenTokenOwnerAddress1, notes.getNoteTxs(1).getNote().getValue() - zenTokenFee, - zenTokenOwnerKey2, blockingStubFull)); - - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "0", memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo3.get(), notes.getNoteTxs(2), - shieldOutList, - zenTokenOwnerAddress1, notes.getNoteTxs(2).getNote().getValue() - zenTokenFee, - zenTokenOwnerKey2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress1, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress1, zenTokenOwnerKey1, blockingStubFull); - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress2, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress2, zenTokenOwnerKey2, blockingStubFull); - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress3, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress3, zenTokenOwnerKey3, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java deleted file mode 100644 index 59abb2ec9f4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken008 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 1 * zenTokenFee + 1; - private Long sendTokenAmount = 1 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = false, - description = "Public send 1 token to shield transaction") - public void test1Shield2ShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield 1 token memo in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "1", memo); - Assert.assertFalse(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, costTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - Assert.assertTrue(sendNote.getValue() == 1); - - } - - @Test(enabled = false, - description = "Shield send 0 token to shield transaction") - public void test2Shield2ShieldTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - zenTokenFee * 2, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - logger.info("token balance is " + afterAssetBalance); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield costFee token memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - //logger.info(); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, zenTokenFee * 2, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - receiverShieldAddressInfo = PublicMethed.generateShieldAddress(); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "0", memo); - - //Wrong proof - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - //Amount is -1 - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "-1", memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - receiverNote = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note:" + receiverNote.toString()); - Assert.assertTrue(receiverNote.getValue() == 0); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java deleted file mode 100644 index af1d45fb2e4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java +++ /dev/null @@ -1,222 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - Optional receiverAddressInfo; - String receiverAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey4.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 5 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(zenTokenOwnerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = zenTokenOwnerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(zenTokenOwnerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, zenTokenOwnerAddress, zenTokenOwnerKey, - blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, - description = "Public to shield transaction with mutisign") - public void test1Public2ShieldTransaction() { - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeBalance = PublicMethed - .queryAccount(zenTokenOwnerAddress, blockingStubFull).getBalance(); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethedForMutiSign.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull, 0, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Long afterNetUsed = PublicMethed.getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - logger.info("Before net:" + beforeNetUsed); - logger.info("After net:" + afterNetUsed); - Assert.assertEquals(beforeNetUsed, afterNetUsed); - final Long afterBalance = PublicMethed - .queryAccount(zenTokenOwnerAddress, blockingStubFull).getBalance(); - Assert.assertTrue(beforeBalance - afterBalance == multiSignFee); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertTrue(receiverShieldTokenAmount == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, - description = "When from is shield,sign this transaction is forbidden") - public void test2ShieldFromShouldNotSign() { - receiverAddressInfo = PublicMethed.generateShieldAddress(); - receiverAddress = shieldAddressInfo.get().getAddress(); - logger.info("receiver address:" + shieldAddress); - - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverAddress, - "" + (note.getValue() - zenTokenFee), memo); - - Assert.assertFalse(PublicMethedForMutiSign.sendShieldCoin( - null, 321321, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull, 0, ownerKeyString)); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 321321, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - Assert.assertFalse(PublicMethed.getSpendResult(shieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethedForMutiSign.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, - zenTokenOwnerKey, blockingStubFull, ownerKeyString); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java deleted file mode 100644 index d1c162f770c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java +++ /dev/null @@ -1,260 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken010 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - - } - - @Test(enabled = false, description = "Shield to itself transaction") - public void test1Shield2ShieldTransaction() { - shieldOutList.clear(); - memo = "Send shield to itself memo1 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - - memo = "Send shield to itself memo2 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendNote.getValue() - 2 * zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - Assert.assertTrue(notes.getNoteTxs(1).getNote().getValue() == zenTokenFee); - Assert.assertTrue(notes.getNoteTxs(2).getNote().getValue() - == sendNote.getValue() - 2 * zenTokenFee); - Assert.assertEquals(notes.getNoteTxs(1).getNote().getPaymentAddress(), - notes.getNoteTxs(2).getNote().getPaymentAddress()); - Assert.assertEquals(notes.getNoteTxs(1).getTxid(), notes.getNoteTxs(2).getTxid()); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.getShieldNotesByOvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 2); - } - - @Test(enabled = false, description = "From shield only have one zenToken fee") - public void test2Shield2ShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, 2 * zenTokenFee, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - shieldOutList.clear(); - memo = "Send shield to itself memo1 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "0", memo); - - memo = "Send shield to itself memo2 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - logger.info("index 0:" + notes.getNoteTxs(0).getNote().getValue()); - logger.info("index 1:" + notes.getNoteTxs(1).getNote().getValue()); - logger.info("index 2:" + notes.getNoteTxs(2).getNote().getValue()); - Assert.assertTrue(notes.getNoteTxs(1).getNote().getValue() == 0); - Assert.assertTrue(notes.getNoteTxs(2).getNote().getValue() == 0); - Assert.assertEquals(notes.getNoteTxs(1).getNote().getPaymentAddress(), - notes.getNoteTxs(2).getNote().getPaymentAddress()); - Assert.assertEquals(notes.getNoteTxs(1).getTxid(), notes.getNoteTxs(2).getTxid()); - } - - @Test(enabled = false, description = "From public and to public is same one") - public void test3Public2ShieldAndPublicItselfTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - ecKey1 = new ECKey(Utils.getRandom()); - zenTokenOwnerAddress = ecKey1.getAddress(); - zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull).getAccountId(), - blockingStubFull); - final Long beforeBalance = PublicMethed.queryAccount(zenTokenOwnerAddress, blockingStubFull) - .getBalance(); - shieldOutList.clear(); - memo = "From public and to public is same one memo in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + 2 * zenTokenFee, memo); - - Assert.assertFalse(PublicMethed - .sendShieldCoin(zenTokenOwnerAddress, costTokenAmount, null, null, shieldOutList, - zenTokenOwnerAddress, 7 * zenTokenFee, zenTokenOwnerKey, blockingStubFull)); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull).getAccountId(), - blockingStubFull); - Long afterBalance = PublicMethed.queryAccount(zenTokenOwnerAddress, blockingStubFull) - .getBalance(); - - Assert.assertEquals(beforeAssetBalance, afterAssetBalance); - Assert.assertEquals(beforeBalance, afterBalance); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 0); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java deleted file mode 100644 index 9287e92c0b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken011 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = false, description = "Test get new shield address ") - public void test1Shield2ShieldTransaction() { - sendShieldAddress = blockingStubFull.getNewShieldedAddress(GrpcAPI.EmptyMessage.newBuilder() - .build()).getPaymentAddress(); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java deleted file mode 100644 index 99d26ce145e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java +++ /dev/null @@ -1,206 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token001 extends ZenTrc20Base { - - List shieldOutList = new ArrayList<>(); - Optional shieldAddressOptionalInfo1; - Optional shieldAddressOptionalInfo2; - Optional shieldAddressOptionalInfo3; - ShieldAddressInfo shieldAddressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo3 = new ShieldAddressInfo(); - String assetIssueId; - ShieldNoteInfo shieldNote1; - ShieldNoteInfo shieldNote2; - ShieldNoteInfo shieldNote3; - String memo; - String sk; - String d1; - String d2; - String d3; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String pkD2; - String pkD3; - String paymentAddress1; - String paymentAddress2; - String paymentAddress3; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - //Args.getInstance().setFullNodeAllowShieldedTransaction(true); - //PublicMethed.printAddress(foundationZenTokenKey); - //PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = true, description = "Get spending key by http") - public void test01GetSpendingKey() { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sk = responseContent.getString("value"); - logger.info("sk: " + sk); - - } - - @Test(enabled = true, description = "Get diversifier by http") - public void test02GetDiversifier() { - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d1 = responseContent.getString("d"); - logger.info("d1: " + d1); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d2 = responseContent.getString("d"); - logger.info("d2: " + d2); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d3 = responseContent.getString("d"); - logger.info("d3: " + d3); - } - - @Test(enabled = true, description = "Get expanded spending key by http") - public void test03GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - logger.info("ask: " + ask); - logger.info("nsk: " + nsk); - logger.info("ovk: " + ovk); - } - - @Test(enabled = true, description = "Get AK from ASK by http") - public void test04GetAkFromAsk() { - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ak = responseContent.getString("value"); - logger.info("ak: " + ak); - } - - @Test(enabled = true, description = "Get Nk from Nsk by http") - public void test05GetNkFromNsk() { - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - nk = responseContent.getString("value"); - logger.info("nk: " + nk); - } - - @Test(enabled = true, description = "Get incoming viewing Key by http") - public void test06GetIncomingViewingKey() { - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ivk = responseContent.getString("ivk"); - logger.info("ivk: " + ivk); - } - - @Test(enabled = true, description = "Get Zen Payment Address by http") - public void test07GetZenPaymentAddress() { - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - System.out.println("pkd1: " + pkD1); - System.out.println("address1: " + paymentAddress1); - shieldAddressInfo1.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo1.setD(new DiversifierT(ByteArray.fromHexString(d1))); - shieldAddressInfo1.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo1.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo1.setPkD(ByteArray.fromHexString(pkD1)); - shieldAddressOptionalInfo1 = Optional.of(shieldAddressInfo1); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD2 = responseContent.getString("pkD"); - paymentAddress2 = responseContent.getString("payment_address"); - System.out.println("pkd2: " + pkD2); - System.out.println("address2: " + paymentAddress2); - shieldAddressInfo2.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo2.setD(new DiversifierT(ByteArray.fromHexString(d2))); - shieldAddressInfo2.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo2.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo2.setPkD(ByteArray.fromHexString(pkD2)); - shieldAddressOptionalInfo2 = Optional.of(shieldAddressInfo2); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d3); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD3 = responseContent.getString("pkD"); - paymentAddress3 = responseContent.getString("payment_address"); - System.out.println("pkd3: " + pkD3); - System.out.println("address3: " + paymentAddress3); - shieldAddressInfo3.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo3.setD(new DiversifierT(ByteArray.fromHexString(d3))); - shieldAddressInfo3.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo3.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo3.setPkD(ByteArray.fromHexString(pkD3)); - shieldAddressOptionalInfo3 = Optional.of(shieldAddressInfo3); - } - - @Test(enabled = true, description = "Get rcm by http") - public void test08GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java deleted file mode 100644 index 67518968128..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java +++ /dev/null @@ -1,200 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token002 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo; - private JSONArray noteTxs; - private Long publicFromAmount = getRandomLongAmount(); - - @Test(enabled = true, description = "Get new shield account by http") - public void test01GetNewShieldAccountByHttp() { - response = getNewShieldedAddress(httpnode); - shieldAccountInfo = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo); - Assert.assertEquals(shieldAccountInfo.getString("sk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ask").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("nsk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ovk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ak").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("nk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ivk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("d").length(), 22); - Assert.assertEquals(shieldAccountInfo.getString("pkD").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("payment_address").length(), 81); - - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - } - - @Test(enabled = true, description = "Create mint parameters by http") - public void test02MintByHttp() { - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm((httpnode))); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 250000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 250000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - - } - - - @Test(enabled = true, description = "Scan shield TRC20 note by http") - public void test03ScanTrc20NodeByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - logger.info(noteTxs.toJSONString()); - Assert.assertEquals(noteTxs.size(), 2); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getJSONObject("note").getLong("value"), publicFromAmount); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getJSONObject("note").getString("payment_address"), - shieldAccountInfo.getString("payment_address")); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getString("txid"), txid); - } - - @Test(enabled = true, description = "Shield trc20 burn by http") - public void test04ShiledTrc20BurnByHttp() { - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(0)); - - logger.info(shieldSpends.toJSONString()); - - response = createShieldContractParametersForBurn(httpnode, shieldAccountInfo, shieldSpends, - zenTrc20TokenOwnerAddressString, publicFromAmount); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - Assert.assertEquals(noteTxs.getJSONObject(0).getLong("to_amount"), publicFromAmount); - Assert.assertEquals(noteTxs.getJSONObject(0).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(0).getString("txid"), txid); - } - - - @Test(enabled = true, description = "Shield trc20 burn with ask by http") - public void test05ShiledTrc20BurnWithoutAskByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(1)); - - logger.info(shieldSpends.toJSONString()); - - response = createShieldContractParametersWithoutAskForBurn(httpnode, shieldAccountInfo, - shieldSpends, zenTrc20TokenOwnerAddressString, publicFromAmount); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo, - shieldedTrc20Parameters.getString("message_hash"), noteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20BurnContract(httpnode, - shieldedTrc20Parameters, spendAuthSigArray, publicFromAmount, - zenTrc20TokenOwnerAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - } - - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java deleted file mode 100644 index 5fdc4e8039a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java +++ /dev/null @@ -1,289 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token003 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo1; - private JSONObject shieldAccountInfo2; - private JSONArray account1IvkNoteTxs = new JSONArray(); - private JSONArray account2IvkNoteTxs = new JSONArray(); - private JSONArray account1OvkNoteTxs = new JSONArray(); - private JSONArray account2OvkNoteTxs = new JSONArray(); - private Long publicFromAmount = getRandomLongAmount(); - private Long account1Receive1V2Amount = 10L; - private Long account2Receive1V2Amount = publicFromAmount - account1Receive1V2Amount; - private Long account1Receive2V2Amount = 13L; - private Long account2Receive2V2Amount = publicFromAmount - + account2Receive1V2Amount - account1Receive2V2Amount; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Prepare for transfer") - public void prepareForTransfer() { - //Create two shield account - response = getNewShieldedAddress(httpnode); - shieldAccountInfo1 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo1); - - response = getNewShieldedAddress(httpnode); - shieldAccountInfo2 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo2); - //Send two mint to shield account 1 - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - } - - - @Test(enabled = true, description = "Transfer type with 1V1 by http") - public void test01TransferTypeWith1V1ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(0)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 1); - } - - @Test(enabled = true, description = "Transfer type with 1V2 by http") - public void test02TransferTypeWith1V2ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(1)); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive1V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive1V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 3); - } - - - @Test(enabled = true, description = "Transfer type with 2V2 by http") - public void test03TransferTypeWith2V2ByHttp() { - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(0)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(1)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive2V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo2, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account2OvkNoteTxs.size(), 2); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - - } - - @Test(enabled = true, description = "Transfer type with 2V1 by http") - public void test04TransferTypeWith2V1ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(2)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(3)); - Long account1Receive2V1Amount = account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getLong("value") - + account1IvkNoteTxs.getJSONObject(3).getJSONObject("note").getLong("value"); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V1Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 4); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - - } - - - @Test(enabled = true, description = "Query is shielded trc20 contract note spent on " - + "solidity by http") - public void test05QueryIsShieldedTrc20ContractNoteSpentByHttp() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnSolidity(httpSolidityNode, - shieldAccountInfo1, account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnSolidity(httpSolidityNode, - shieldAccountInfo1, account1IvkNoteTxs.getJSONObject(3))); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java deleted file mode 100644 index c874776919f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java +++ /dev/null @@ -1,376 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token004 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo1; - private JSONObject shieldAccountInfo2; - private JSONArray account1IvkNoteTxs = new JSONArray(); - private JSONArray account2IvkNoteTxs = new JSONArray(); - private JSONArray account1OvkNoteTxs = new JSONArray(); - private JSONArray account2OvkNoteTxs = new JSONArray(); - private Long publicFromAmount = getRandomLongAmount(); - private Long account1Receive1V2Amount = 10L; - private Long account2Receive1V2Amount = publicFromAmount - account1Receive1V2Amount; - private Long account1Receive2V2Amount = 13L; - private Long account2Receive2V2Amount = publicFromAmount + account2Receive1V2Amount - - account1Receive2V2Amount; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Prepare for transfer without ask") - public void prepareForTransfer() { - //Create two shield account - response = getNewShieldedAddress(httpnode); - shieldAccountInfo1 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo1); - - response = getNewShieldedAddress(httpnode); - shieldAccountInfo2 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo2); - //Send two mint to shield account 1 - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - - @Test(enabled = true, description = "Transfer type with 1V1 without ask by http") - public void test01TransferTypeWith1V1WithoutAskByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(0)); - HttpMethed.waitToProduceOneBlock(httpnode); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs - .getJSONObject(0).getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 1); - } - - @Test(enabled = true, description = "Transfer type with 1V2 without ask by http") - public void test02TransferTypeWith1V2WithoutAskByHttp() { - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(1)); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive1V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive1V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - //spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 3); - } - - - @Test(enabled = true, description = "Transfer type with 2V2 without ask by http") - public void test03TransferTypeWith2V2WithoutAskByHttp() { - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(0)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(1)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive2V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo2, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo2, - shieldedTrc20Parameters.getString("message_hash"), account2IvkNoteTxs.getJSONObject(0) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - - JSONObject spendAuthSig2 = createSpendAuthSig(httpnode, shieldAccountInfo2, - shieldedTrc20Parameters.getString("message_hash"), account2IvkNoteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account2OvkNoteTxs.size(), 2); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - - } - - @Test(enabled = true, description = "Transfer type with 2V1 without ask by http") - public void test04TransferTypeWith2V1WithoutAskByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(2)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(3)); - Long account1Receive2V1Amount = account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getLong("value") - + account1IvkNoteTxs.getJSONObject(3).getJSONObject("note").getLong("value"); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V1Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - - JSONObject spendAuthSig2 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(3) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig2); - - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 4); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnPbft(httpPbftNode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnPbft(httpPbftNode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - - } - - - @Test(enabled = true, description = "Scan note by ivk and ovk on solidity and pbft by http") - public void test05ScanNoteByIvkAndOvkOnSOlidityAndPbftByHttp() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - JSONArray account1IvkNoteTxsOnSolidity = scanShieldTrc20NoteByIvkOnSolidity(httpSolidityNode, - shieldAccountInfo1); - Assert.assertEquals(account1IvkNoteTxs, account1IvkNoteTxsOnSolidity); - JSONArray account1IvkNoteTxsOnPbft = scanShieldTrc20NoteByIvkOnPbft(httpPbftNode, - shieldAccountInfo1); - Assert.assertEquals(account1IvkNoteTxs, account1IvkNoteTxsOnPbft); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - JSONArray account1OvkNoteTxsOnSolidity = scanShieldTrc20NoteByOvkOnSolidity(httpSolidityNode, - shieldAccountInfo1); - Assert.assertEquals(account1OvkNoteTxs, account1OvkNoteTxsOnSolidity); - JSONArray account1OvkNoteTxsOnPbft = scanShieldTrc20NoteByOvkOnPbft(httpPbftNode, - shieldAccountInfo1); - Assert.assertEquals(account1OvkNoteTxs, account1OvkNoteTxsOnPbft); - - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - JSONArray account2IvkNoteTxsOnSolidity = scanShieldTrc20NoteByIvkOnSolidity(httpSolidityNode, - shieldAccountInfo2); - Assert.assertEquals(account2IvkNoteTxs, account2IvkNoteTxsOnSolidity); - JSONArray account2IvkNoteTxsOnPbft = scanShieldTrc20NoteByIvkOnPbft(httpPbftNode, - shieldAccountInfo2); - Assert.assertEquals(account2IvkNoteTxs, account2IvkNoteTxsOnPbft); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - JSONArray account2OvkNoteTxsOnSolidity = scanShieldTrc20NoteByOvkOnSolidity(httpSolidityNode, - shieldAccountInfo2); - Assert.assertEquals(account2OvkNoteTxs, account2OvkNoteTxsOnSolidity); - JSONArray account2OvkNoteTxsOnPbft = scanShieldTrc20NoteByOvkOnPbft(httpPbftNode, - shieldAccountInfo2); - Assert.assertEquals(account2OvkNoteTxs, account2OvkNoteTxsOnPbft); - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java deleted file mode 100644 index 998a97a9322..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java +++ /dev/null @@ -1,197 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token005 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo; - private JSONObject shieldReceiverAccountInfo; - private JSONArray noteTxs; - private Long publicFromAmount = getRandomLongAmount(); - - /** - * constructor. - */ - - @BeforeClass(enabled = true, description = "Get new shield account by http") - public void createTwoNote() { - response = getNewShieldedAddress(httpnode); - shieldAccountInfo = HttpMethed.parseResponseContent(response); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm((httpnode))); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - } - - @Test(enabled = true, description = "Shield trc20 burn to one T and one S by http") - public void test01ShiledTrc20BurnToOnePublicAndOneShieldByHttp() { - response = getNewShieldedAddress(httpnode); - shieldReceiverAccountInfo = HttpMethed.parseResponseContent(response); - - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(0)); - - logger.info(shieldSpends.toJSONString()); - - Long toShieldAmount = 9L; - Long toPublicAmount = publicFromAmount - toShieldAmount; - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, toShieldAmount, - shieldReceiverAccountInfo.getString("payment_address"), getRcm(httpnode)); - - response = createShieldContractParametersForBurn(httpnode, shieldAccountInfo, shieldSpends, - zenTrc20TokenOwnerAddressString, toPublicAmount, shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - - Assert.assertEquals(noteTxs.getJSONObject(0).getJSONObject("note") - .getLong("value"), toShieldAmount); - Assert.assertEquals(noteTxs.getJSONObject(0).getJSONObject("note") - .getString("payment_address"), shieldReceiverAccountInfo.getString("payment_address")); - - Assert.assertEquals(noteTxs.getJSONObject(1).getLong("to_amount"), toPublicAmount); - Assert.assertEquals(noteTxs.getJSONObject(1).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(1).getString("txid"), txid); - } - - - @Test(enabled = true, description = "Shield trc20 burn without ask to one " - + "public and one shield by http") - public void test02ShiledTrc20BurnWithoutAskToOnePublicAndOneShieldByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(1)); - - Long toShieldAmount = 8L; - Long toPublicAmount = publicFromAmount - toShieldAmount; - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, toShieldAmount, - shieldReceiverAccountInfo.getString("payment_address"), getRcm(httpnode)); - - response = createShieldContractParametersWithoutAskForBurn(httpnode, shieldAccountInfo, - shieldSpends, zenTrc20TokenOwnerAddressString, toPublicAmount, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo, - shieldedTrc20Parameters.getString("message_hash"), noteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20BurnContract(httpnode, - shieldedTrc20Parameters, spendAuthSigArray, toPublicAmount, - zenTrc20TokenOwnerAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - - Assert.assertEquals(noteTxs.getJSONObject(2).getJSONObject("note") - .getLong("value"), toShieldAmount); - Assert.assertEquals(noteTxs.getJSONObject(2).getJSONObject("note") - .getString("payment_address"), shieldReceiverAccountInfo.getString("payment_address")); - - Assert.assertEquals(noteTxs.getJSONObject(3).getLong("to_amount"), toPublicAmount); - Assert.assertEquals(noteTxs.getJSONObject(3).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(3).getString("txid"), txid); - - } - - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java deleted file mode 100644 index ee61c9996c9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java +++ /dev/null @@ -1,84 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token001 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Check shield contract deploy success") - public void test01checkShieldContractDeploySuccess() { - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - infoById = PublicMethed - .getTransactionInfoById(deployShieldTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //scalingFactor() - } - - @Test(enabled = true, description = "View scaling factor test") - public void test02ViewScalingFactor() { - String txid = PublicMethed.triggerContract(shieldAddressByte, - "scalingFactor()", "", false, - 0, maxFeeLimit, zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(shieldAddressByte, "scalingFactor()", - "", false, 0, 0, "0", 0, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - String scalingFactor = PublicMethed - .bytes32ToString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals("00000000000000000000000000000001", - scalingFactor); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java deleted file mode 100644 index f118553d496..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token002 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Send shield trc20 from T account to shield account") - public void test01ShieldTrc20TransactionByTypeMint() throws Exception { - //Query account before mint balance - final Long beforeMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Generate new shiled account and set note memo - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - logger.info(mint + ":" + txid); - logger.info(mint + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 250000); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Query account after mint balance - Long afterMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract after mint balance - Long afterMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - Assert.assertEquals(BigInteger.valueOf(beforeMintAccountBalance - afterMintAccountBalance), - publicFromAmount); - Assert.assertEquals(BigInteger.valueOf(afterMintShieldAccountBalance - - beforeMintShieldAccountBalance), publicFromAmount); - - GrpcAPI.DecryptNotesTRC20 note = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - logger.info("" + note); - - Assert.assertEquals(note.getNoteTxs(0).getNote().getValue(), publicFromAmount.longValue()); - Assert.assertEquals(note.getNoteTxs(0).getNote().getPaymentAddress(), - receiverShieldAddressInfo.get().getAddress()); - Assert.assertEquals(note.getNoteTxs(0).getNote().getMemo(), ByteString.copyFromUtf8(memo)); - Assert.assertEquals(note.getNoteTxs(0).getTxid(), infoById.get().getId()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java deleted file mode 100644 index 81ee7e32b8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java +++ /dev/null @@ -1,216 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token003 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 receiverNote; - long senderPosition; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for transfer test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type transfer") - public void test01ShieldTrc20TransactionWithTypeTransfer() throws Exception { - final Long beforeMintShieldContractBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - String transferMemo = "Transfer type test " + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, transferMemo, blockingStubFull); - inputShieldAddressList.add(senderShieldAddressInfo.get()); - //inputNoteList.add(senderNote); - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - //String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan sender note - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - - logger.info("" + receiverNote); - Assert.assertEquals(receiverNote.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo)); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getPaymentAddress(), - receiverShieldAddressInfo.get().getAddress()); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - senderNote = scanShieldedTrc20NoteByOvk(senderShieldAddressInfo.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + senderNote:" + senderNote); - - final Long afterMintShieldContractBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - Assert.assertEquals(beforeMintShieldContractBalance, afterMintShieldContractBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type transfer without ask") - public void test02ShieldTrc20TransactionWithTypeTransferWithoutAsk() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Scan receiver note prepare for without type of transfer - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - String transferMemo = "Transfer type without ask test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, senderShieldAddressInfo.get() - .getAddress(), - "" + publicFromAmount, transferMemo, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(receiverShieldAddressInfo.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - receiverNote, inputShieldAddressList, shieldOutList, "", null, 0L, - blockingStubFull, blockingStubSolidity); - - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - - logger.info("" + senderNote); - Assert.assertEquals(senderNote.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo)); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getValue(), - publicFromAmount.longValue()); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getPaymentAddress(), - senderShieldAddressInfo.get().getAddress()); - - //logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(receiverNote.getNoteTxs(0).getIsSpent(), true); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java deleted file mode 100644 index bad605d1cc9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java +++ /dev/null @@ -1,307 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token004 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional secondSenderShieldAddressInfo; - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - List inputNoteList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 secondSenderNote; - long senderPosition; - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddressbyte = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String receiverAddressString = PublicMethed.getAddressString(receiverKey); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for burn test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - //Generate new shiled account for burn to one public and one shield - secondSenderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - - memo = "Create a note for burn to one public and one shield test " - + System.currentTimeMillis(); - sendShieldAddress = secondSenderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + secondSenderNote); - senderPosition = secondSenderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn") - public void test01ShieldTrc20TransactionWithTypeBurn() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - //String burnMemo = "Burn type test " + System.currentTimeMillis(); - inputShieldAddressList.add(senderShieldAddressInfo.get()); - BigInteger receiveAmount = publicFromAmount; - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, null, receiverAddressString, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), receiveAmount); - - senderNote = scanShieldedTrc20NoteByOvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(ByteArray.toHexString(senderNote.getNoteTxs(0) - .getTxid().toByteArray()), txid); - Assert.assertEquals(senderNote.getNoteTxs(0).getToAmount(), publicFromAmount.toString()); - - String toAddress = ByteArray.toHexString(senderNote.getNoteTxs(0) - .getTransparentToAddress().toByteArray()); - String receiverHexString = ByteArray.toHexString(PublicMethed.getFinalAddress(receiverKey)); - Assert.assertEquals(toAddress, receiverHexString); - - - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction to one T and one S with type burn") - public void test02ShieldTrc20TransactionWithTypeBurnToOnePublicAndOneShield() throws Exception { - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.clear(); - inputShieldAddressList.add(secondSenderShieldAddressInfo.get()); - BigInteger shieldReceiveAmount = BigInteger.valueOf(9L); - BigInteger receiveAmount = publicFromAmount.subtract(shieldReceiveAmount); - - ShieldedAddressInfo receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull).get(); - String receiverShieldAddress = receiverShieldAddressInfo.getAddress(); - String memo = "Burn to one shield and one public test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + shieldReceiveAmount, memo, blockingStubFull); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - secondSenderNote, inputShieldAddressList, shieldOutList, receiverAddressString, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), receiveAmount); - - secondSenderNote = scanShieldedTrc20NoteByOvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - logger.info(secondSenderNote.toString()); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - shieldReceiveAmount.longValue()); - - Assert.assertEquals(ByteArray.toHexString(secondSenderNote.getNoteTxs(1) - .getTxid().toByteArray()), txid); - Assert.assertEquals(secondSenderNote.getNoteTxs(1).getToAmount(), receiveAmount.toString()); - - String toAddress = ByteArray.toHexString(secondSenderNote.getNoteTxs(1) - .getTransparentToAddress().toByteArray()); - String receiverHexString = ByteArray.toHexString(PublicMethed.getFinalAddress(receiverKey)); - Assert.assertEquals(toAddress, receiverHexString); - - GrpcAPI.DecryptNotesTRC20 receiverSenderNote - = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo, - blockingStubFull); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0) - .getIsSpent(), false); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0) - .getNote().getValue(), shieldReceiveAmount.longValue()); - Assert.assertEquals(ByteArray.toHexString(receiverSenderNote - .getNoteTxs(0).getTxid().toByteArray()), txid); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java deleted file mode 100644 index dcd9feeb8ee..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java +++ /dev/null @@ -1,276 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token005 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional secondSenderShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - List inputNoteList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 secondSenderNote; - GrpcAPI.DecryptNotesTRC20 receiverSenderNote; - long senderPosition; - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddressbyte = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String receiverAddressString = PublicMethed.getAddressString(receiverKey); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for burn withoutask test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Create second mint parameters - memo = "Create a note for burn to one public and one shield withoutask test " - + System.currentTimeMillis(); - secondSenderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String sesendShieldAddress = secondSenderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sesendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn and without ask") - public void test01ShieldTrc20TransactionWithTypeBurnWithoutAsk() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.add(senderShieldAddressInfo.get()); - BigInteger receiveAmount = publicFromAmount; - //Create burn parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, null, receiverAddressString, receiverAddressbyte, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), - receiveAmount); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn to one " - + "T and one Z address and without ask") - public void test02ShieldTrc20TransactionWithTypeBurnWithoutAsk() throws Exception { - //Scan sender note - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.clear(); - inputShieldAddressList.add(secondSenderShieldAddressInfo.get()); - BigInteger shieldReceiveAmount = BigInteger.valueOf(0); - BigInteger receiveAmount = publicFromAmount.subtract(shieldReceiveAmount); - - ShieldedAddressInfo receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull).get(); - String receiverShieldAddress = receiverShieldAddressInfo.getAddress(); - String memo = "Burn to one shield and one public test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + shieldReceiveAmount, memo, blockingStubFull); - - //Create burn parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - secondSenderNote, inputShieldAddressList, shieldOutList, receiverAddressString, - receiverAddressbyte, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), - receiveAmount); - - receiverSenderNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo, - blockingStubFull); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0).getIsSpent(), false); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0).getNote() - .getValue(), shieldReceiveAmount.longValue()); - Assert.assertEquals(ByteArray.toHexString(receiverSenderNote.getNoteTxs(0) - .getTxid().toByteArray()), txid); - - secondSenderNote = scanShieldedTrc20NoteByOvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - logger.info(secondSenderNote.toString()); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - shieldReceiveAmount.longValue()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java deleted file mode 100644 index 079e46de22d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java +++ /dev/null @@ -1,525 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token006 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - Optional shieldAddressInfo1; - Optional shieldAddressInfo2; - String shieldAddress1; - String shieldAddress2; - private BigInteger publicFromAmount; - private BigInteger shield1ReceiveAmountFor1to2; - private BigInteger shield2ReceiveAmountFor1to2; - private BigInteger shield1ReceiveAmountFor2to2; - private BigInteger shield2ReceiveAmountFor2to2; - private BigInteger shield1ReceiveAmountFor2to1; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 shield1Note; - GrpcAPI.DecryptNotesTRC20 shield2Note; - long senderPosition; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - shieldAddressInfo1 = getNewShieldedAddress(blockingStubFull); - shieldAddressInfo2 = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for transfer test " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - Assert.assertEquals(shield1Note.getNoteTxs(0).getIsSpent(), false); - logger.info("" + shield1Note); - senderPosition = shield1Note.getNoteTxs(0).getPosition(); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 1 to 2") - public void test01ShieldTrc20TransferWith1To2() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Prepare parameters - final String transferMemo1 = "1 to 2 for shieldAddressInfo1 " + System.currentTimeMillis(); - final String transferMemo2 = "1 to 2 for shieldAddressInfo2 " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldAddress2 = shieldAddressInfo2.get().getAddress(); - shield1ReceiveAmountFor1to2 = BigInteger.valueOf(30); - shield2ReceiveAmountFor1to2 = publicFromAmount.subtract(shield1ReceiveAmountFor1to2); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor1to2, transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress2, - "" + shield2ReceiveAmountFor1to2, transferMemo2, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo1.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - shield1Note, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 1 to 2 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getValue(), - shield1ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getValue(), - shield2ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(0).getIsSpent(), true); - - //Scan 1 to 2 ovk note - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield1Note); - Assert.assertEquals(shield1Note.getNoteTxsCount(), 2); - - Assert.assertEquals(shield1Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getValue(), - shield1ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getValue(), - shield2ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 2 to 2") - public void test02ShieldTrc20TransferWith2To2() throws Exception { - //Create a new note for 2 to 2 - String memo = "Create a new note for transfer test " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - - final GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(shield1Note.getNoteTxs(1)) - .addNoteTxs(shield1Note.getNoteTxs(2)).build(); - - //Prepare parameters - final String transferMemo1 = "2 to 2 for shieldAddressInfo1 " + System.currentTimeMillis(); - final String transferMemo2 = "2 to 2 for shieldAddressInfo2 " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldAddress2 = shieldAddressInfo2.get().getAddress(); - shield1ReceiveAmountFor2to2 = BigInteger.valueOf(5); - shield2ReceiveAmountFor2to2 = publicFromAmount.add(shield1ReceiveAmountFor1to2) - .subtract(shield1ReceiveAmountFor2to2); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor2to2, transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress2, - "" + shield2ReceiveAmountFor2to2, transferMemo2, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo1.get()); - inputShieldAddressList.add(shieldAddressInfo1.get()); - - //Create transfer parameters - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 2 to 2 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(3).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getValue(), - shield1ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getValue(), - shield2ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(1).getIsSpent(), true); - Assert.assertEquals(shield1Note.getNoteTxs(2).getIsSpent(), true); - - //Scan 2 to 2 ovk note - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield1Note); - Assert.assertEquals(shield1Note.getNoteTxsCount(), 4); - - Assert.assertEquals(shield1Note.getNoteTxs(2).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getValue(), - shield1ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(3).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getValue(), - shield2ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 2 to 1") - public void test03ShieldTrc20TransferWith2To1() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - - //Prepare parameters - final String transferMemo1 = "2 to 1 for shieldAddressInfo1 " + System.currentTimeMillis(); - - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shield1ReceiveAmountFor2to1 = BigInteger.valueOf(shield2Note.getNoteTxs(0) - .getNote().getValue() + shield2Note.getNoteTxs(1).getNote().getValue()); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor2to1, transferMemo1, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo2.get()); - inputShieldAddressList.add(shieldAddressInfo2.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - shield2Note, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 2 to 1 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(4).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getValue(), - shield1ReceiveAmountFor2to1.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getIsSpent(), true); - Assert.assertEquals(shield2Note.getNoteTxs(1).getIsSpent(), true); - - //Scan 2 to 1 ovk note - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield2Note); - Assert.assertEquals(shield2Note.getNoteTxsCount(), 1); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getValue(), - shield1ReceiveAmountFor2to1.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Scan shield trc20 note by ivk and ovk on solidity") - public void test04ScanShieldTrc20NoteByIvkAndOvkOnSolidity() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield1NoteOnSolidity - = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield1Note, shield1NoteOnSolidity); - - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield2NoteOnSolidity - = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield2Note, shield2NoteOnSolidity); - - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - shield1NoteOnSolidity - = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield1Note, shield1NoteOnSolidity); - - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - shield2NoteOnSolidity - = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield2Note, shield2NoteOnSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Scan shield trc20 note by ivk and ovk on pbft") - public void test04ScanShieldTrc20NoteByIvkAndOvkOnPbft() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield1NoteOnPbft - = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield1Note, shield1NoteOnPbft); - - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield2NoteOnPbft - = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield2Note, shield2NoteOnPbft); - - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - shield1NoteOnPbft - = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield1Note, shield1NoteOnPbft); - - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - shield2NoteOnPbft - = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield2Note, shield2NoteOnPbft); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Query is shield trc20 note spend on solidity and pbft") - public void test05IsShieldTrc20NoteSpendOnSolidityAndPbft() throws Exception { - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull), true); - - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull), - getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull, blockingStubSolidity)); - - Assert.assertTrue(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull, blockingStubPbft)); - - boolean spend = getTrc20SpendResult(shieldAddressInfo1.get(),shield1Note.getNoteTxs(1), - blockingStubFull); - - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo1.get(), shield1Note.getNoteTxs(1), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo1.get(), shield1Note.getNoteTxs(1), - blockingStubFull, blockingStubPbft)); - - spend = getTrc20SpendResult(shieldAddressInfo2.get(),shield2Note.getNoteTxs(0), - blockingStubFull); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(0), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(0), - blockingStubFull, blockingStubPbft)); - - spend = getTrc20SpendResult(shieldAddressInfo2.get(),shield2Note.getNoteTxs(1), - blockingStubFull); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(1), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(1), - blockingStubFull, blockingStubPbft)); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java b/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java deleted file mode 100644 index b0343368d1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java +++ /dev/null @@ -1,439 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class AttackSendcoin { - - private static final long now = System.currentTimeMillis(); - private static long start; - private static long end; - private static long beforeFromBalance; - private static long beforeNormal1Balance; - private static long beforeNormal2Balance; - private static long beforeNormal3Balance; - private static long beforeNormal4Balance; - private static long beforeAttackBalance; - private static long afterFromBalance; - private static long afterNormal1Balance; - private static long afterNormal2Balance; - private static long afterNormal3Balance; - private static long afterNormal4Balance; - private static long afterAttackBalance; - //testng001、testng002、testng003、testng004 - //Devaccount - private final String testKey001 = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - //Zion - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - //Sun - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - //Normal1 - private final String normalKey001 = - "36c0710378a34634e6baba0d3a79d7439a81183030147e7f4a0dd43bfed1a32f"; - //Normal2 - private final String normalKey002 = - "a6bfbcf98bbe07770bf79bc6b2970bae0992771c1dcbf24cc063a3f033f17fbf"; - //Normal3 - private final String normalKey003 = - "8273f6b26202526cbffb77569b830c1ba8a920040e77f6f26062a67315580ed7"; - //Normal4 - private final String normalKey004 = - "271c824fcb55f04a9f86f768424a80edeb26ab79cf12aa56643b595f689c008a"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] attackAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] normal1Address = PublicMethed.getFinalAddress(normalKey001); - private final byte[] normal2Address = PublicMethed.getFinalAddress(normalKey002); - private final byte[] normal3Address = PublicMethed.getFinalAddress(normalKey003); - private final byte[] normal4Address = PublicMethed.getFinalAddress(normalKey004); - private final Long sendNromal1Amount = 1L; - private final Long sendNromal2Amount = 2L; - private final Long sendNromal3Amount = 3L; - private final Long sendNromal4Amount = 4L; - private final Long attackAmount = 5L; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - return true; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - final Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - final Account attackInfo = PublicMethed.queryAccount(testKey001, blockingStubFull); - final Account normal1Info = PublicMethed.queryAccount(normalKey001, blockingStubFull); - final Account normal2Info = PublicMethed.queryAccount(normalKey002, blockingStubFull); - final Account normal3Info = PublicMethed.queryAccount(normalKey003, blockingStubFull); - final Account normal4Info = PublicMethed.queryAccount(normalKey004, blockingStubFull); - beforeFromBalance = fromInfo.getBalance(); - beforeNormal1Balance = normal1Info.getBalance(); - beforeNormal2Balance = normal2Info.getBalance(); - beforeNormal3Balance = normal3Info.getBalance(); - beforeNormal4Balance = normal4Info.getBalance(); - beforeAttackBalance = attackInfo.getBalance(); - start = System.currentTimeMillis(); - } - - //@Test(enabled = true) - @Test(enabled = false, threadPoolSize = 200, invocationCount = 200) - public void freezeAndSendcoin() throws InterruptedException { - - Integer i = 0; - Random rand = new Random(); - Integer randNum = 0; - Integer n = 0; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - if (randNum == 3) { - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - /* PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull);*/ - } - - if (randNum == 0) { - PublicMethed.sendcoin(normal1Address, sendNromal1Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 1) { - PublicMethed.sendcoin(normal2Address, sendNromal2Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 2) { - PublicMethed.sendcoin(normal3Address, sendNromal3Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 3) { - PublicMethed.sendcoin(normal4Address, sendNromal4Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - //Print the duration. - end = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end - start)); - - //Print 6 account balance information. - final Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - final Account attackInfo = PublicMethed.queryAccount(testKey001, blockingStubFull); - final Account normal1Info = PublicMethed.queryAccount(normalKey001, blockingStubFull); - final Account normal2Info = PublicMethed.queryAccount(normalKey002, blockingStubFull); - final Account normal3Info = PublicMethed.queryAccount(normalKey003, blockingStubFull); - final Account normal4Info = PublicMethed.queryAccount(normalKey004, blockingStubFull); - - afterFromBalance = fromInfo.getBalance(); - afterNormal1Balance = normal1Info.getBalance(); - afterNormal2Balance = normal2Info.getBalance(); - afterNormal3Balance = normal3Info.getBalance(); - afterNormal4Balance = normal4Info.getBalance(); - afterAttackBalance = attackInfo.getBalance(); - - logger.info("attack transaction success num is " - + (afterAttackBalance - beforeAttackBalance) / attackAmount); - logger.info("Normal 1 transaction success num is " - + (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount); - logger.info("Normal 2 transaction success num is " - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount); - logger.info("Normal 3 transaction success num is " - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount); - logger.info("Normal 4 transaction success num is " - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount); - - Long totalSuccessNum = (afterAttackBalance - beforeAttackBalance) / attackAmount - + (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount; - logger.info("Total success transaction is " + Long.toString(totalSuccessNum)); - - Long normaltotalSuccessNum = (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount; - logger.info("Total normal success transaction is " + Long.toString(normaltotalSuccessNum)); - - Integer blockTimes = 0; - Integer blockTransNum = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - logger.info("The block num " + Long.toString(currentNum) - + "total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - //logger.info(Integer.toString(currentBlock.getTransactionsList() - // .get(0).getRawData().getContract(0).getTypeValue())); - - Integer normal1Num = 0; - Integer normal2Num = 0; - Integer normal3Num = 0; - Integer normal4Num = 0; - Integer attackNum = 0; - Long temp = 0L; - for (Integer m = 0; m < currentBlock.getTransactionsCount(); m++) { - try { - temp = currentBlock.getTransactions(m).getRawData().getContract(0).getParameter() - .unpack(TransferContract.class).getAmount(); - } catch (InvalidProtocolBufferException e) { - e.printStackTrace(); - } - if (temp == sendNromal1Amount) { - normal1Num++; - } - if (temp == sendNromal2Amount) { - normal2Num++; - } - if (temp == sendNromal3Amount) { - normal3Num++; - } - if (temp == sendNromal4Amount) { - normal4Num++; - } - if (temp == attackAmount) { - attackNum++; - } - } - logger.info("Block num " + Long.toString(currentNum) + ", Attack num is " - + Integer.toString(attackNum)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 1 num is " - + Integer.toString(normal1Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 2 num is " - + Integer.toString(normal2Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 3 num is " - + Integer.toString(normal3Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 4 num is " - + Integer.toString(normal4Num)); - blockTransNum = blockTransNum + currentBlock.getTransactionsCount(); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - logger.info("Total block record num is " + Integer.toString(blockTransNum)); - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java b/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java deleted file mode 100644 index 5d60cee81f3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java +++ /dev/null @@ -1,410 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ContinueVote { - - //testng001、testng002、testng003、testng004 - - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = false, threadPoolSize = 30, invocationCount = 30) - public void testVoteWitness() { - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - Base58.encode58Check(fromAddress); - logger.info(Base58.encode58Check(fromAddress)); - String voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - - Boolean ret = false; - Integer i = 0; - while (fromInfo.getBalance() > 100000000) { - randNum = rand.nextInt(30) + 1; - voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, Integer.toString(randNum)); - if (fromInfo.getFrozen(0).getFrozenBalance() < 10000000) { - PublicMethed.freezeBalance(fromAddress, 10000000000L, 3, testKey002, blockingStubFull); - } - ret = voteWitness(smallVoteMap, fromAddress, testKey002); - if (ret) { - logger.info("This vote num is " + Integer.toString(randNum)); - logger.info("Now the fromaddress vote is " + Long.toString(fromInfo - .getVotes(0).getVoteCount())); - logger.info(Integer.toString(i++)); - } - fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - accountNetMessage = blockingStubFull.getAccountNet(request); - logger.info("Now the from net used is " + Long.toString(accountNetMessage.getNetUsed())); - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - //Assert.assertTrue(afterVote.getVotes(j).getVoteCount() == Long - // .parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java b/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java deleted file mode 100644 index b9a2b68ea9f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Creatasset { - - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcwedcv"; - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 1025000000L; - private static final long netCostMeasure = 200L; - private static String name = "c_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForAssetIssue016); - logger.info(transferAssetCreateKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 20, invocationCount = 20) - public void createAssetissue() throws InterruptedException { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Account fromAccountInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - //Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,100000000, 3, testKey002, - // blockingStubFull)); - - Integer i = 0; - //GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - // .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - //logger.info(Integer.toString(assetIssueList.getAssetIssueCount())); - Boolean ret = false; - Boolean transRet = false; - Boolean updateRet = false; - Boolean participateRet = false; - Random rand = new Random(); - Integer randNum; - - while (fromAccountInfo.getBalance() > 1025000000) { - randNum = rand.nextInt(4); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(asset016Address, sendAmount, fromAddress, testKey002, blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - name = "c_" + Long.toString(System.currentTimeMillis()); - totalSupply = now; - - ret = PublicMethed - .createAssetIssue(asset016Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue016, - blockingStubFull); - - if (ret) { - updateRet = PublicMethed - .updateAsset(asset016Address, tooLongDescription.getBytes(), tooLongUrl.getBytes(), - 4000L, 4000L, - testKeyForAssetIssue016, blockingStubFull); - if (updateRet) { - logger.info("update succesfully"); - } - logger.info(Integer.toString(i++)); - //assetIssueList = blockingStubFull - // .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - //logger.info("assetissue num is " + Integer.toString(assetIssueList.getAssetIssueCount())); - try { - randNum = rand.nextInt(10000) + 3000; - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - transRet = PublicMethed.transferAsset(toAddress, name.getBytes(), - 1L, asset016Address, testKeyForAssetIssue016, blockingStubFull); - participateRet = PublicMethed - .participateAssetIssue(asset016Address, name.getBytes(), 1L, toAddress, testKey003, - blockingStubFull); - if (participateRet) { - logger.info("participate success"); - } - logger.info(testKeyForAssetIssue016); - if (transRet) { - logger.info("transfer success"); - } - - } - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - fromAccountInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - ret = false; - updateRet = false; - participateRet = false; - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - try { - //randNum = rand.nextInt(10000) + 3000; - Thread.sleep(6000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - }*/ - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java b/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java deleted file mode 100644 index 87b662dc8ce..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java +++ /dev/null @@ -1,234 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Base64; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CreateAddressAndKey { - - private static String path = "/Users/wangzihe/Documents/"; - private static String filename = "/Users/wangzihe/Sites/postmanUsedKeyandAddress"; - private static String filenameTemp; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - /** - * constructor. - */ - public static boolean createFile(String fileName, String filecontent) { - Boolean bool = false; - filenameTemp = fileName;//文件路径+名称+文件类型 - File file = new File(filenameTemp); - try { - //如果文件不存在,则创建新的文件 - if (!file.exists()) { - file.createNewFile(); - bool = true; - System.out.println("success create file,the file is " + filenameTemp); - //创建文件成功后,写入内容到文件里 - writeFileContent(filenameTemp, filecontent); - } else { - clearInfoForFile(filenameTemp); - writeFileContent(filenameTemp, filecontent); - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - return bool; - } - - /** - * constructor. - */ - public static void clearInfoForFile(String fileName) { - File file = new File(fileName); - try { - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fileWriter = new FileWriter(file); - fileWriter.write(""); - fileWriter.flush(); - fileWriter.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * constructor. - */ - public static boolean writeFileContent(String filepath, String newstr) throws IOException { - Boolean bool = false; - String filein = newstr + "\r\n"; - String temp = ""; - - FileInputStream fis = null; - InputStreamReader isr = null; - BufferedReader br = null; - FileOutputStream fos = null; - PrintWriter pw = null; - try { - File file = new File(filepath); - fis = new FileInputStream(file); - isr = new InputStreamReader(fis); - br = new BufferedReader(isr); - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; (temp = br.readLine()) != null; i++) { - buffer.append(temp); - buffer = buffer.append(System.getProperty("line.separator")); - } - buffer.append(filein); - - fos = new FileOutputStream(file); - pw = new PrintWriter(fos); - pw.write(buffer.toString().toCharArray()); - pw.flush(); - bool = true; - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } finally { - if (pw != null) { - pw.close(); - } - if (fos != null) { - fos.close(); - } - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (fis != null) { - fis.close(); - } - } - return bool; - } - - /** - * constructor. - */ - - public static boolean delFile(String fileName) { - Boolean bool = false; - filenameTemp = path + fileName + ".txt"; - File file = new File(filenameTemp); - try { - if (file.exists()) { - file.delete(); - bool = true; - } - } catch (Exception e) { - // TODO: handle exception - } - return bool; - } - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - - } - - @Test(enabled = false) - public void createAddressesAndKeys() { - Integer i = 0; - String accountIndex; - String keyIndex; - JsonObject jsonobject = new JsonObject(); - JsonArray jsonarray = new JsonArray(); - HashMap addressAndKey = new HashMap(); - while (i++ < 600) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] address = ecKey1.getAddress(); - String addressString = ByteArray.toHexString(address); - byte[] key = ecKey1.getPrivKeyBytes(); - final String keyString = ByteArray.toHexString(key); - - logger.info(ByteArray.toStr(Base64.encode(key))); - logger.info(ByteArray.toStr(Base64.encode(address))); - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", addressString); - userBaseObj2.addProperty("key", keyString); - //userBaseObj2.addProperty("address",ByteArray.toStr(Base64.encode(address))); - //userBaseObj2.addProperty("key", ByteArray.toStr(Base64.encode(key))); - jsonarray.add(userBaseObj2); - } - Gson gson = new Gson(); - String jsonMap = gson.toJson(addressAndKey); - //createFile(filename,jsonobject.toString()); - createFile(filename, jsonarray.toString()); - - } - - @Test(enabled = true) - public void create() { - Integer i = 0; - String accountIndex; - String keyIndex; - JsonObject jsonobject = new JsonObject(); - JsonArray jsonarray = new JsonArray(); - HashMap addressAndKey = new HashMap(); - while (i++ < 600) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] address = ecKey1.getAddress(); - String key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ArrayList accountList = new ArrayList(); - accountList = PublicMethed.getAddressInfo(key); - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", accountList.get(1)); - userBaseObj2.addProperty("key", accountList.get(0)); - jsonarray.add(userBaseObj2); - } - Gson gson = new Gson(); - String jsonMap = gson.toJson(addressAndKey); - //createFile(filename,jsonobject.toString()); - createFile(filename, jsonarray.toString()); - - } - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - } -} - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java b/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java deleted file mode 100644 index c9c43d1e02c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java +++ /dev/null @@ -1,321 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class FreezeAndSendcoin { - - private static final long now = System.currentTimeMillis(); - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final Long sendAmount = 10000000L; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeAddress = ecKey1.getAddress(); - String testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - return true; - } - - - - //@Test(enabled = false) - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - /* Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4); - try { - randNum = rand.nextInt(20000); - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - - logger.info(testKeyForFreeze); - logger.info(transferAssetCreateKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false, threadPoolSize = 500, invocationCount = 1000) - public void freezeAndSendcoin() throws InterruptedException { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeAddress = ecKey1.getAddress(); - String testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Account toAccountInfo = PublicMethed.queryAccount(testKey003, blockingStubFull); - Account freezeAccountInfo = PublicMethed.queryAccount(testKeyForFreeze, blockingStubFull); - - Integer i = 0; - Boolean ret = false; - Boolean sendRet = false; - Boolean updateRet = false; - Boolean participateRet = false; - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - - while (toAccountInfo.getBalance() > 10000009L) { - randNum = rand.nextInt(3); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - freezeBalance(freezeAddress, 3000000L, 3L, testKeyForFreeze, blockingStubFull); - PublicMethed - .sendcoin(freezeAddress, sendAmount, toAddress, testKey003, blockingStubFull); - - ret = freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - - if (ret) { - logger.info("New account freeze success " + Integer.toString(i)); - sendRet = PublicMethed.sendcoin(toAddress, 6000000L, freezeAddress, - testKeyForFreeze, blockingStubFull); - if (sendRet) { - logger.info("This account transfer coin back. " + Integer.toString(i)); - freezeAccountInfo = PublicMethed.queryAccount(testKeyForFreeze, blockingStubFull); - logger.info("This account now has balance is " + Long - .toString(freezeAccountInfo.getBalance())); - - } - - } - - unFreezeBalance(freezeAddress, testKeyForFreeze); - withdrawBalance(freezeAddress, testKeyForFreeze); - - ecKey1 = new ECKey(Utils.getRandom()); - freezeAddress = ecKey1.getAddress(); - testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - toAccountInfo = PublicMethed.queryAccount(testKey003, blockingStubFull); - logger.info("Now the toaddress balance is " + Long.toString(toAccountInfo.getBalance())); - NumberMessage beforeGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info("Now total transaction is " + Long.toString(beforeGetTotalTransaction.getNum())); - ret = false; - sendRet = false; - i++; - - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - try { - //randNum = rand.nextInt(10000) + 3000; - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - }*/ - - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java b/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java deleted file mode 100644 index 0a4ed47dbb1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java +++ /dev/null @@ -1,223 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.db.Manager; -import org.tron.protos.Protocol; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class Fuzzytest { - - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static long start; - private static long end; - private static long now = System.currentTimeMillis(); - private static String name = "AssetIssue016_" + Long.toString(now); - private static long totalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset017Address = ecKey1.getAddress(); - String testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Manager dbManager; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("failed reason is " + ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000, 3, testKey002, - blockingStubFull)); - while (assetIssueList.getAssetIssueCount() <= 1) { - //Sendcoin to this account - Assert.assertTrue(PublicMethed - .sendcoin(asset017Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - now = System.currentTimeMillis(); - name = "AssetIssue017_" + Long.toString(now); - totalSupply = now; - Assert.assertTrue(createAssetIssue(asset017Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, - 1L, testKeyForAssetIssue017, blockingStubFull)); - - assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - - ecKey1 = new ECKey(Utils.getRandom()); - asset017Address = ecKey1.getAddress(); - testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - } - } - - @Test(enabled = false, threadPoolSize = 5, invocationCount = 5) - public void tooManyChannelFull() { - Integer i = 0; - while (i++ < 20000) { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - GrpcAPI.NodeList nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - if (i % 100 == 0) { - logger.info(Integer.toString(i)); - } - - } - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - }*/ - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java b/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java deleted file mode 100644 index e42128f5cae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java +++ /dev/null @@ -1,341 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ParticipateAssetIssue { - - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 10250000000L; - private static String name = "PartAssetIssue_" + Long.toString(now); - private static long beforeCreateAssetIssueBalance; - private static long afterCreateAssetIssueBalance; - private static long afterParticipateAssetIssueBalance; - private static long start1; - private static long end1; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 300000000L; - Long publicFreeAssetNetLimit = 300000000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] createAddress = ecKey1.getAddress(); - String testKeyForCreate = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String testKeyForParticipate = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - //logger.info("transaction == null"); - } else { - //logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForCreate); - logger.info(testKeyForParticipate); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - //Send coin to 2 account. - Assert.assertTrue(PublicMethed.sendcoin(createAddress, sendAmount, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(participateAssetAddress, sendAmount, - fromAddress, testKey002, blockingStubFull)); - //Participate account freeze balance to get bandwidth. - Assert.assertTrue(PublicMethed.freezeBalance(participateAssetAddress, - 10000000L, 3, testKeyForParticipate, blockingStubFull)); - //Create an asset issue. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(createAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 10L, 10L, testKeyForCreate, blockingStubFull)); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - final Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - final Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, - blockingStubFull); - - Map assetIssueMap = new HashMap(); - - Long temp = 0L; - assetIssueMap = createInfo.getAssetMap(); - for (String key : assetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : assetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - beforeCreateAssetIssueBalance = temp; - start1 = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 250, invocationCount = 250) - public void testParticipateAssetIssue() throws InterruptedException { - Integer i = 0; - Integer randNum; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - participateAssetIssue(createAddress, name.getBytes(), - 1, participateAssetAddress, testKeyForParticipate, blockingStubFull); - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - //Print the duration. - end1 = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end1 - start1)); - - Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - - Map createAssetIssueMap = new HashMap(); - - Long temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - Map participateAssetIssueMap = new HashMap(); - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + " at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + " at the end"); - logger.info("Create account reduce balance " + Long.toString(beforeCreateAssetIssueBalance - - afterCreateAssetIssueBalance)); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - Integer blockTimes = 0; - Integer blockTransParticipateNum = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - logger.info("The block num " + Long.toString(currentNum) - + " total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - createAssetIssueMap = new HashMap(); - participateAssetIssueMap = new HashMap(); - - temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + "at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + "at the end"); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java b/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java deleted file mode 100644 index 34b753c0229..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java +++ /dev/null @@ -1,398 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class SuperWitnessAllowance { - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 10009000000L; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String createWitnessUrl = "http://www.createwitnessurl.com"; - String updateWitnessUrl = "http://www.updatewitnessurl.com"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testInvaildToApplyBecomeWitness() { - Assert.assertFalse(createWitness(INVAILD_ADDRESS, createUrl, testKey002)); - } - - //@Test(enabled = true,threadPoolSize = 10, invocationCount = 10) - @Test(enabled = false) - public void testCreate130Witness() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - while (witnessList.getWitnessesCount() < 130) { - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - logger.info(lowBalTest); - Assert.assertTrue(sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002)); - Assert.assertTrue(PublicMethed.freezeBalance(lowBalAddress, 1000000, - 3, lowBalTest, blockingStubFull)); - Assert.assertTrue(createWitness(lowBalAddress, createUrl, lowBalTest)); - String voteStr = Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest)); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(voteWitness(smallVoteMap, lowBalAddress, lowBalTest)); - witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - result = Optional.ofNullable(witnesslist); - witnessList = result.get(); - - } - - } - - //@Test(enabled = true,threadPoolSize = 10, invocationCount = 10) - @Test(enabled = false) - public void testQueryAllowance() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - Integer allowanceNum = 0; - for (Integer i = 0; i < witnessList.getWitnessesCount(); i++) { - /* witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress();*/ - ByteString addressBs = witnessList.getWitnesses(i).getAddress(); - Account request = Account.newBuilder().setAddress(addressBs).build(); - request = blockingStubFull.getAccount(request); - if (request.getAllowance() > 0) { - allowanceNum++; - } - logger.info("Account " + Integer.toString(i) + " allowance is " + Long.toString(request - .getAllowance())); - - } - logger.info("Allowance num is " + Integer.toString(allowanceNum)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Account beforeVote = PublicMethed.queryAccount(priKey, blockingStubFull); - //Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - return true; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java b/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java deleted file mode 100644 index a9b0a6fe02d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java +++ /dev/null @@ -1,371 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class TransferAssetIssue { - - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 10250000000L; - private static String name = "PartAssetIssue_" + Long.toString(now); - private static long beforeCreateAssetIssueBalance; - private static long afterCreateAssetIssueBalance; - private static long afterParticipateAssetIssueBalance; - private static long start1; - private static long end1; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 300000000L; - Long publicFreeAssetNetLimit = 300000000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] createAddress = ecKey1.getAddress(); - String testKeyForCreate = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String testKeyForParticipate = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - //logger.info("transaction == null"); - } else { - //logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForCreate); - logger.info(testKeyForParticipate); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - //Send coin to 2 account. - Assert.assertTrue(PublicMethed.sendcoin(createAddress, sendAmount, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(participateAssetAddress, - sendAmount, fromAddress, testKey002, blockingStubFull)); - //Participate account freeze balance to get bandwidth. - Assert.assertTrue(PublicMethed.freezeBalance(participateAssetAddress, 10000000L, 3, - testKeyForParticipate, blockingStubFull)); - //Create an asset issue. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(createAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 10L, 10L, testKeyForCreate, blockingStubFull)); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - final Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - final Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, - blockingStubFull); - - Map assetIssueMap = new HashMap(); - - Long temp = 0L; - assetIssueMap = createInfo.getAssetMap(); - for (String key : assetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : assetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - beforeCreateAssetIssueBalance = temp; - start1 = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 200, invocationCount = 200) - public void transferAssetIssue() throws InterruptedException { - Integer i = 0; - Integer randNum; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - transferAsset(participateAssetAddress, name.getBytes(), 1, - createAddress, testKeyForCreate, blockingStubFull); - } - } - - /** - * constructor. - */ - - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - //Print the duration. - end1 = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end1 - start1)); - - Map createAssetIssueMap = new HashMap(); - - Long temp = 0L; - Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - Map participateAssetIssueMap = new HashMap(); - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + " at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + " at the end"); - logger.info("Create account reduce balance " + Long.toString(beforeCreateAssetIssueBalance - - afterCreateAssetIssueBalance)); - logger.info("Transfer account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - Integer blockTimes = 0; - Integer blockTransParticipateNum = 0; - Integer useNet = 0; - Integer useFee = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - for (Integer m = 0; m < currentBlock.getTransactionsCount(); m++) { - logger.info(currentBlock.getTransactions(m).getRetList().toString()); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), currentBlock.getTransactions(m) - .getRawData().toByteArray())); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - Optional getTransactionById = Optional.ofNullable(transaction); - if (getTransactionById.get().getRet(0).getFee() > 0) { - logger.info(Long.toString(getTransactionById.get().getRet(0).getFee())); - useFee++; - } else { - logger.info("No use fee"); - useNet++; - } - } - - logger.info("The block num " + Long.toString(currentNum) - + " total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - logger.info("Use Net num is " + Integer.toString(useNet)); - logger.info("Use Fee num is " + Integer.toString(useFee)); - - createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - createAssetIssueMap = new HashMap(); - participateAssetIssueMap = new HashMap(); - - temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + "at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + "at the end"); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java b/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java deleted file mode 100644 index e2ad7c3cf61..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TronDice { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress; - Long maxFeeLimit = 1000000000L; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ArrayList txidList = new ArrayList(); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract008Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(testKey002); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void tronDice() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] tronDiceAddress = ecKey1.getAddress(); - String tronDiceKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed - .sendcoin(tronDiceAddress, 100000000000L, fromAddress, testKey002, blockingStubFull); - String contractName = "TronDice"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TronDice_tronDice"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TronDice_tronDice"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000000L, 100, null, tronDiceKey, tronDiceAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Assert.assertTrue(smartContract.getAbi() != null); - - String txid; - - for (Integer i = 0; i < 100; i++) { - String initParmes = "\"" + "10" + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "rollDice(uint256)", initParmes, false, - 1000000, maxFeeLimit, tronDiceAddress, tronDiceKey, blockingStubFull); - logger.info(txid); - txidList.add(txid); - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - try { - Thread.sleep(20000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Integer successTimes = 0; - Integer failedTimes = 0; - Integer totalTimes = 0; - for (String txid1 : txidList) { - totalTimes++; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - if (infoById.get().getBlockNumber() > 3523732) { - logger.info("blocknum is " + infoById.get().getBlockNumber()); - successTimes++; - } else { - failedTimes++; - } - } - logger.info("Total times is " + totalTimes.toString()); - logger.info("success times is " + successTimes.toString()); - logger.info("failed times is " + failedTimes.toString()); - logger.info("success percent is " + successTimes / totalTimes); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java b/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java deleted file mode 100644 index 295376ed8e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmContract { - - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contract008Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(contract008Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info(Long.toString(PublicMethed.queryAccount(contract008Key, blockingStubFull) - .getBalance())); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract008Address, 1000000L, - 3, 1, contract008Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.buyStorage(50000000L, contract008Address, contract008Key, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(contract008Address, 5000000L, - 3, contract008Key, blockingStubFull)); - - } - - @Test(enabled = false) - public void deployErc721CryptoKitties() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long storageLimit = accountResource.getStorageLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long storageUsage = accountResource.getStorageUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before storage limit is " + Long.toString(storageLimit)); - logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 50000000L; - String contractName = "ERC721"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TvmContract_deployErc721CryptoKitties"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TvmContract_deployErc721CryptoKitties"); - Long m = 0L; - Long freeNet; - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - Long net = accountResource.getFreeNetUsed(); - Account account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - Long netUsed = account.getNetUsage(); - logger.info("before net used is " + Long.toString(netUsed)); - logger.info("before balance is " + account.getBalance()); - - for (Integer i = 0; i < 1; i++) { - byte[] contractAddress = PublicMethed.deployContract("1", abi, code, "", - 30000000L, 0L, 1, null, contract008Key, contract008Address, blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - freeNet = accountResource.getFreeNetUsed(); - energyUsage = accountResource.getEnergyUsed(); - logger.info( - "Time " + Integer.toString(i) + ": energy usage is " + Long.toString(energyUsage - m)); - logger.info("Time " + Integer.toString(i) + ": free net used is " + Long - .toString(freeNet - net)); - account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("after balance is " + account.getBalance()); - netUsed = account.getNetUsage(); - logger.info("after net used is " + Long.toString(netUsed)); - net = freeNet; - m = energyUsage; - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - //SmartContract smartContract = PublicMethed.getContract(contractAddress,blockingStubFull); - - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - //Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - //Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - //logger.info(smartContract.getName()); - //logger.info(smartContract.getAbi().toString()); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - storageLimit = accountResource.getStorageLimit(); - energyUsage = accountResource.getEnergyUsed(); - storageUsage = accountResource.getStorageUsed(); - //Assert.assertTrue(storageUsage > 0); - //Assert.assertTrue(storageLimit > 0); - //Assert.assertTrue(energyLimit > 0); - //Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after storage limit is " + Long.toString(storageLimit)); - logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java deleted file mode 100644 index 139ca70fab5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java +++ /dev/null @@ -1,342 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 0, - blockingStubFull, ownerKeyString); - - Assert.assertNotNull(txid); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 2, blockingStubFull, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java deleted file mode 100644 index 7774d336613..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java +++ /dev/null @@ -1,200 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 9; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Assert.assertTrue(PublicMethedForMutiSign.createAccount( - ownerAddress, newAddress, ownerKey, blockingStubFull, ownerKeyString)); - - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 0, ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergy( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiver( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, null, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccount( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, ownerKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitness( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 9 + 1000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java deleted file mode 100644 index cbec5d977cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - //String contractName = "StorageAndCpu" + Integer.toString(randNum); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getBlockNumber() > 0); - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needcoin); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java deleted file mode 100644 index 3271a36428c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.mutisign; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class WalletTestMutiSign005 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue(balanceBefore - balanceAfter >= needcoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java deleted file mode 100644 index fe735b21119..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java +++ /dev/null @@ -1,120 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CreateAccount2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - //owner account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account007Address = ecKey1.getAddress(); - String account007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //Wait to be create account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(account007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(account007Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateAccount2() { - Account accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - final Long beforeBalance = accountInfo.getBalance(); - AccountNetMessage accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - final Long beforeFreeNet = accountNetInfo.getFreeNetUsed(); - GrpcAPI.Return ret1 = PublicMethed.createAccount2(account007Address, newAccountAddress, - account007Key, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - Long afterBalance = accountInfo.getBalance(); - accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - Long afterFreeNet = accountNetInfo.getFreeNetUsed(); - logger.info(Long.toString(beforeBalance)); - logger.info(Long.toString(afterBalance)); - //When creator has no bandwidth, he can't use the free net. - Assert.assertTrue(afterFreeNet == beforeFreeNet); - //When the creator has no bandwidth, create a new account should spend 0.1TRX. - Assert.assertTrue(beforeBalance - afterBalance == 100000); - } - - @Test(enabled = true) - public void testExceptionCreateAccount2() { - //Try to create an exist account - GrpcAPI.Return ret1 = PublicMethed - .createAccount2(account007Address, account007Address, account007Key, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Account has existed"); - //Try to create an invalid account - byte[] wrongAddress = "wrongAddress".getBytes(); - ret1 = PublicMethed.createAccount2(account007Address, wrongAddress, account007Key, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid account address"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java deleted file mode 100644 index a33ab4abe7b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java +++ /dev/null @@ -1,398 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class CreateAssetIssue2Test { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test-assetissue-001"; - String url = "https://github.com/tronprotocol/wallet-cli/assetissue001"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test() - public void testTransferAssetBandwitchDecreaseWithin10Second2() { - ByteString addressBS1 = ByteString.copyFrom(noBandwitchAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Long start = System.currentTimeMillis() + 2000000; - Long end = System.currentTimeMillis() + 1000000000; - GrpcAPI.Return ret1 = PublicMethed.createAssetIssue2(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - } - - Assert.assertTrue( - transferAsset(toAddress, name.getBytes(), 100L, noBandwitchAddress, noBandwitch)); - //Transfer Asset failed when transfer to yourself - //Assert.assertFalse(transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003)); - Return ret1 = transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Cannot transfer asset to yourself."); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - ret1 = - transferAsset2(fromAddress, name.getBytes(), 9100000000000000000L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : assetBalance is not sufficient."); - //Transfer Asset failed when the transfer amount is 0 - ret1 = transferAsset2(fromAddress, name.getBytes(), 0L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Amount must greater than 0."); - //Transfer Asset failed when the transfer amount is -1 - ret1 = transferAsset2(fromAddress, name.getBytes(), -1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Amount must greater than 0."); - //Transfer failed when you want to transfer to an invalid address - ret1 = transferAsset2(INVAILD_ADDRESS, name.getBytes(), - 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Invalid toAddress"); - //Transfer failed when the asset issue name is not correct. - ret1 = - transferAsset2(fromAddress, (name + "wrong").getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "contract validate error : No asset !"); - //Transfer success. - ret1 = transferAsset2(fromAddress, name.getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - logger.info("Test no asset frozen balance, try to unfreeze asset, no exception. Test OK!!!"); - - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - logger.info("Test not create asset issue, try to unfreeze asset, no exception. Test OK!!!"); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public Return transferAsset2(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferAssetContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - //return true; - } - return ret; - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - UnfreezeAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java deleted file mode 100644 index bc3622f01ba..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java +++ /dev/null @@ -1,352 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class CreateTransaction2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = Base58 - .decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //receipt account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiptAccountAddress = ecKey2.getAddress(); - String receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test - public void testSendCoin2() { - Assert.assertTrue(PublicMethed.sendcoin(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull)); - - logger.info(receiptAccountKey); - Account sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountBeforeBalance = sendAccount.getBalance(); - Assert.assertTrue(sendAccountBeforeBalance == 90000000000L); - Account receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountBeforeBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountBeforeBalance == 0); - //normal sendcoin2 - Return ret1 = PublicMethed.sendcoin2(receiptAccountAddress, 49880000000L, - sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance)); - Assert.assertTrue(sendAccountAfterBalance == 90000000000L - 49880000000L - 100000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountAfterBalance == 49880000000L); - //Send coin failed due to no enough balance. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, 9199999999999999999L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Validate TransferContract error, balance is not sufficient."); - //Send coin failed due to the amount is 0. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, 0L, sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must be greater than 0."); - //Send coin failed due to the amount is -1Trx. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, -1000000L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must be greater than 0.."); - - //Send coin to yourself - ret1 = PublicMethed.sendcoin2(sendAccountAddress, 1000000L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Cannot transfer trx to yourself."); - //transfer all balance - ret1 = PublicMethed.sendcoin2(receiptAccountAddress, 40119900000L, - sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance1 = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance1)); - Assert.assertTrue( - sendAccountAfterBalance1 == 90000000000L - 49880000000L - 100000 - 40119900000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance1 = receiptAccount.getBalance(); - logger.info(Long.toString(receiptAccountAfterBalance1)); - Assert.assertTrue(receiptAccountAfterBalance1 == 49880000000L + 40119900000L); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java deleted file mode 100644 index 19bba10b51f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java +++ /dev/null @@ -1,433 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class CreateaAndUpdateWitness2Test { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 9999000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String createWitnessUrl = "http://www.createwitnessurl.com"; - String updateWitnessUrl = "http://www.updatewitnessurl.com"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testInvaildToApplyBecomeWitness2() { - GrpcAPI.Return ret1 = createWitness2(INVAILD_ADDRESS, createUrl, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid address"); - } - - @Test(enabled = true) - public void testCreateWitness2() { - //If you are already is witness, apply failed - createWitness(fromAddress, createUrl, testKey002); - GrpcAPI.Return ret1 = createWitness2(fromAddress, createUrl, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Witness[415624c12e308b03a1a6b21d9b86e3942fac1ab92b] " - + "has existed"); - //balance is not enouhg,try to create witness. - Assert.assertTrue(sendcoin(lowBalAddress, 1000000L, fromAddress, testKey002)); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : balance < AccountUpgradeCost"); - //Send enough coin to the apply account to make that account - // has ability to apply become witness. - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - Assert.assertTrue(sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002)); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } - } - - @Test(enabled = true) - public void testUpdateWitness2() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - //null url, update failed - GrpcAPI.Return ret1 = updateWitness2(lowBalAddress, wrongUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid url"); - //Content space and special char, update success - ret1 = updateWitness2(lowBalAddress, updateSpaceUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //update success - ret1 = updateWitness2(lowBalAddress, updateUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } else { - logger.info("Update witness case had been test.This time skip it."); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public GrpcAPI.Return updateWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - 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 1253cdc8e0d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java +++ /dev/null @@ -1,478 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class FreezeBalance2Test { - - private final String noFrozenBalanceTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] noFrozenAddress = PublicMethed.getFinalAddress(noFrozenBalanceTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = true) - public void testFreezeBalance2() { - //Freeze failed when freeze amount is large than currently balance. - Return ret1 = freezeBalance2(fromAddress, 9000000000000000000L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be less than accountBalance"); - //Freeze failed when freeze amount less than 1Trx - 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"); - //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); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - //Unfreeze balance failed when 3 days hasn't come. - ret1 = unFreezeBalance2(fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : It's not time to unfreeze."); - //Freeze failed when freeze amount is 0. - ret1 = freezeBalance2(fromAddress, 0L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be positive"); - //Freeze failed when freeze amount is -1. - ret1 = freezeBalance2(fromAddress, -1L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be positive"); - //Freeze failed when freeze duration is -1. - ret1 = freezeBalance2(fromAddress, 1000000L, -1L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - //Freeze failed when freeze duration is 0. - ret1 = freezeBalance2(fromAddress, 1000000L, 0L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - - try { - Thread.sleep(16000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Freeze balance success. - ret1 = PublicMethed.freezeBalance2(fromAddress, 1000000L, 3L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } - - @Test(enabled = true) - public void testUnFreezeBalance2() { - //Unfreeze failed when there is no freeze balance. - Return ret1 = unFreezeBalance2(noFrozenAddress, noFrozenBalanceTestKey); - logger.info("Test unfreezebalance"); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : no frozenBalance(BANDWIDTH)"); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return response; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return ret; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Return unFreezeBalance2(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java deleted file mode 100644 index 3667882e0c9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java +++ /dev/null @@ -1,178 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByLatestNum2Test { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLatestNum2() { - // - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(3).build(); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.isPresent()); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 3); - Assert.assertTrue(getBlockByLatestNum.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue( - getBlockByLatestNum.get().getBlock(1).getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse( - getBlockByLatestNum.get().getBlock(2).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - logger.info("TestGetBlockByLatestNum ok!!!"); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(0).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(2).getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionNum2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(-1).build(); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - - numberMessage = NumberMessage.newBuilder().setNum(0).build(); - blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - - numberMessage = NumberMessage.newBuilder().setNum(100).build(); - blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(10).getBlockid().isEmpty()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java deleted file mode 100644 index 6ff1a358c89..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByLimitNext2 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLimitNext2() { - // - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(2); - builder.setEndNum(4); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.isPresent()); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 2); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).hasBlockHeader()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse(getBlockByLimitNext.get().getBlock(0).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLimitNext.get().getBlock(1).getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionLimitNext2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - //From -1 to 1 - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(-1); - builder.setEndNum(1); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //check o block is empty - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).getBlockid().isEmpty()); - //From 3 to 3 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(3); - builder.setEndNum(3); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //check the third block is empty - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(3).getBlockid().isEmpty()); - //From 4 to 2 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(4); - builder.setEndNum(2); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(4).getBlockid().isEmpty()); - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(999999990); - builder.setEndNum(999999999); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(999999990).getBlockid().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java deleted file mode 100644 index e71b2c041e1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java +++ /dev/null @@ -1,265 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByNum2Test { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetBlockByNum2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - /* Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubFull.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader());*/ - - //Query the first block - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - GrpcAPI.BlockExtention firstBlock = blockingStubFull.getBlockByNum2(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(firstBlock.getBlockid().isEmpty()); - - //Query the zero block - NumberMessage.Builder builder21 = NumberMessage.newBuilder(); - builder2.setNum(0); - GrpcAPI.BlockExtention zeroBlock = blockingStubFull.getBlockByNum2(builder21.build()); - Assert.assertTrue(zeroBlock.hasBlockHeader()); - Assert.assertTrue(zeroBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(zeroBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(zeroBlock.getBlockid().isEmpty()); - - //Query the -1 block - NumberMessage.Builder builder22 = NumberMessage.newBuilder(); - builder2.setNum(-1); - GrpcAPI.BlockExtention nagtiveBlock = blockingStubFull.getBlockByNum2(builder22.build()); - Assert.assertTrue(nagtiveBlock.hasBlockHeader()); - Assert.assertTrue(nagtiveBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(nagtiveBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(nagtiveBlock.getBlockid().isEmpty()); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock = blockingStubFull.getBlockByNum2(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(lastSecondBlock.getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByNumFromSolidity2() { - GrpcAPI.BlockExtention currentBlock = blockingStubSolidity - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - GrpcAPI.BlockExtention firstBlock = blockingStubSolidity.getBlockByNum2(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - Assert.assertFalse(firstBlock.getBlockid().isEmpty()); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock = blockingStubSolidity.getBlockByNum2(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - Assert.assertFalse(lastSecondBlock.getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockById2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - ByteString currentHash = currentBlock.getBlockHeader().getRawData().getParentHash(); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(currentHash).build(); - Block setIdOfBlock = blockingStubFull.getBlockById(request); - Assert.assertTrue(setIdOfBlock.hasBlockHeader()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - logger.info(Long.toString(setIdOfBlock.getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - setIdOfBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlock.getBlockHeader() - .getRawData().getNumber()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("By ID test succesfully"); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public GrpcAPI.BlockExtention getBlock2(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java deleted file mode 100644 index e1e66fc1ae2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class GetNowBlock2Test { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test - public void testCurrentBlock2() { - //Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock is " + Long - .toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertFalse(currentBlock.getBlockid().isEmpty()); - - //Improve coverage. - currentBlock.equals(currentBlock); - //Block newBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.BlockExtention newBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - newBlock.equals(currentBlock); - newBlock.hashCode(); - newBlock.getSerializedSize(); - newBlock.getTransactionsCount(); - newBlock.getTransactionsList(); - Assert.assertFalse(newBlock.getBlockid().isEmpty()); - } - - @Test - public void testCurrentBlockFromSolidity2() { - GrpcAPI.BlockExtention currentBlock = blockingStubSolidity - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock in soliditynode is " + Long - .toString(currentBlock.getBlockHeader().getRawData().getNumber())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java deleted file mode 100644 index b3774396a1a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java +++ /dev/null @@ -1,220 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class GetTransactionsFromThis2Test { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String notexist01 = - "DCB620820121A866E4E25905DC37F5025BFA5420B781C69E1BC6E1D83038C88A"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = false) - public void testgetTransactionsFromThis2() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - Optional gettransactionsfromthis2 = Optional - .ofNullable(transactionListExtention); - - if (gettransactionsfromthis2.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, - testKey002, blockingStubFull)); - } - - Assert.assertTrue(gettransactionsfromthis2.isPresent()); - Integer beforecount = gettransactionsfromthis2.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse( - gettransactionsfromthis2.get().getTransaction(j).getTransaction().getRawData() - .getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsFromThisByInvaildAddress2() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - Optional gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java deleted file mode 100644 index 399ca531578..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java +++ /dev/null @@ -1,234 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class GetTransactionsToThis2 { - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = - Base58.decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = - Base58.decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String notexist01 = - "DCB620820121A866E4E25905DC37F5025BFA5420B781C69E1BC6E1D83038C88A"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = true) - public void testgetTransactionsToThis2() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(toAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - - Optional gettransactionstothis2 = Optional - .ofNullable(transactionListExtention); - - if (gettransactionstothis2.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - } - - Assert.assertTrue(gettransactionstothis2.isPresent()); - Integer beforecount = gettransactionstothis2.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse( - gettransactionstothis2.get().getTransaction(j).getTransaction().getRawData() - .getContractList().isEmpty()); - } - } - - @Test(enabled = true) - public void testgetTransactionsToThisByInvaildAddress2() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - Optional gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java deleted file mode 100644 index dea87ebc8ef..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ParticipateAssetIssue2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] participateAccountAddress = ecKey1.getAddress(); - String participateAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetIssueAccount002 = ecKey2.getAddress(); - String testKeyForAssetIssueAccount002 = ByteArray.toHexString(ecKey2 - .getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testParticipateAssetissue2() { - ByteString addressBS1 = ByteString.copyFrom(participateAccountAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(participateAccountAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - //Create a new Asset Issue - Assert.assertTrue(PublicMethed.createAssetIssue(participateAccountAddress, - name, totalSupply, 1, 1, System.currentTimeMillis() + 2000, - System.currentTimeMillis() + 1000000000, 1, description, url, - 2000L, 2000L, 1L, 1L, - participateAccountKey, blockingStubFull)); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - - } - - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Participate AssetIssue success - logger.info(name); - //Freeze amount to get bandwitch. - Assert.assertTrue(PublicMethed.freezeBalance(toAddress, 10000000, 3, testKey003, - blockingStubFull)); - - //The amount is large than the total supply, participate failed. - Return ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), 9100000000000000000L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No enough balance !"); - //The asset issue name is not correct, participate failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - (name + "wrong").getBytes(), 100L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - //The amount is 0, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), 0L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0!"); - - //The amount is -1, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), -1L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0!"); - //The asset issue owner address is not correct, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(fromAddress, name.getBytes(), 100L, - toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java deleted file mode 100644 index 0e1b80e1557..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java +++ /dev/null @@ -1,402 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TransferAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test-assetissue-001"; - String url = "https://github.com/tronprotocol/wallet-cli/assetissue001"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test() - public void testTransferAssetBandwitchDecreaseWithin10Second2() { - ByteString addressBS1 = ByteString.copyFrom(noBandwitchAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - Return ret1 = PublicMethed.createAssetIssue2(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - - } - - Return ret1 = transferAsset2(toAddress, name.getBytes(), 100L, noBandwitchAddress, noBandwitch); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Transfer Asset failed when transfer to yourself - ret1 = transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Cannot transfer asset to yourself."); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - ret1 = - transferAsset2(fromAddress, name.getBytes(), 9100000000000000000L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : assetBalance is not sufficient."); - //Transfer Asset failed when the transfer amount is 0 - ret1 = transferAsset2(fromAddress, name.getBytes(), 0L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0."); - //Transfer Asset failed when the transfer amount is -1 - ret1 = transferAsset2(fromAddress, name.getBytes(), -1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0."); - ret1 = - transferAsset2(fromAddress, (name + "wrong").getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : No asset !"); - //Transfer success. - ret1 = transferAsset2(fromAddress, name.getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - logger.info("Test no asset frozen balance, try to unfreeze asset, no exception. Test OK!!!"); - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - logger.info("Test not create asset issue, try to unfreeze asset, no exception. Test OK!!!"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public Return transferAsset2(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - } - return ret; - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java deleted file mode 100644 index 2be9b42c6a1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java +++ /dev/null @@ -1,632 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class UnfreezeAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = Base58 - .decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private static final String shortname = "a"; - private static final String tooLongName = "qazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAssetIssuename = "中文都名字"; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final long totalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //get account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true) - public void testGetAllAssetIssue2() { - Return ret1 = PublicMethed.sendcoin2(lowBalAddress, 2124500000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21240500000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - ByteString addressBS1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull.getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - - //if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 100000; - Long end = System.currentTimeMillis() + 1000000000; - //Freeze amount is large than total supply, create asset issue failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 9000000000000000000L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply cannot exceed total supply"); - //Freeze day is 0, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 100L, 0L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Freeze amount is 0, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 0L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply must be greater than 0!"); - //Freeze day is -1, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 1000L, 1000L, - 1000L, -1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Freeze amount is -1, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - -1L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply must be greater than 0!"); - //Freeze day is 3653(10 years + 1 day), create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3653L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Start time is late than end time. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - end, start, 2, description, url, 10000L, 10000L, - 1L, 2L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : End time should be greater than start time"); - //Start time is early than currently time. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start - 1000000L, end, 2, description, url, 10000L, - 10000L, 1L, 2L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Start time should be greater than HeadBlockTime"); - //totalSupply is zero. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, 0L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TotalSupply must greater than 0!"); - //Totalsupply is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, -1L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TotalSupply must greater than 0!"); - //TrxNum is zero. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 0, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TrxNum must greater than 0!"); - //TrxNum is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, -1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TrxNum must greater than 0!"); - //IcoNum is 0. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 0, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Num must greater than 0!"); - //IcoNum is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, -1, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Num must greater than 0!"); - //The asset issue name is null. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, "", totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The asset issue name is large than 33 char. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, tooLongName, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The asset issue name is chinese name. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, chineseAssetIssuename, totalSupply, 1, - 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The URL is null. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, "", 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //The URL is too long. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, tooLongUrl, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //The description is too long, create failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, tooLongDescription, url, 10000L, - 10000L, 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid description"); - - //FreezeBalance - Assert.assertTrue(PublicMethed.freezeBalance(lowBalAddress, 10000000L, 3, lowBalTest, - blockingStubFull)); - //Create success - start = System.currentTimeMillis() + 6000; - end = System.currentTimeMillis() + 1000000000; - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Test not in the duration time, participate failed. - ret1 = PublicMethed.participateAssetIssue2(lowBalAddress, name.getBytes(), 1L, - toAddress, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No longer valid period!"); - //Test another address try to create the same name asset issue, create failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress2, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest2, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "contract validate error : Token exists"); - - try { - Thread.sleep(4000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Integer.toString(assetIssueList.getAssetIssue(0).getFrozenSupplyCount())); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupplyCount() == 1); - //Assert.assertTrue(assetIssueList.getAssetIssue(j).getFrozenSupplyCount() > 0); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupply(0).getFrozenAmount() > 0); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupply(0).getFrozenDays() > 0); - - //Test one account only can create one asset issue. - start = System.currentTimeMillis() + 3000; - end = System.currentTimeMillis() + 1000000000; - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, shortname, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : An account can only issue one asset"); - logger.info("FROM ADDRESS create asset issue in this case!!!"); - - assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - for (Integer j = 0; j < assetIssueList.getAssetIssueCount(); j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue"); - } - - //Improve coverage. - assetIssueList.equals(assetIssueList); - assetIssueList.equals(null); - GrpcAPI.AssetIssueList newAssetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - assetIssueList.equals(newAssetIssueList); - assetIssueList.hashCode(); - assetIssueList.getSerializedSize(); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setFreeAssetNetLimit(10000); - builder.setPublicFreeAssetNetLimit(10000); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean unFreezeAsset2(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeAsset2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java deleted file mode 100644 index cae5235ebd0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java +++ /dev/null @@ -1,961 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class UpdateAccount2Test { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue_" + Long.toString(now); - private static final long TotalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String mostLongNamePlusOneChar = "1abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - String mostLongName = "abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - //System.out.println(); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey1.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - PublicMethed.printAddress(lowBalTest); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testCreateAccount2() { - Account noCreateAccount = queryAccount(lowBalTest, blockingStubFull); - if (noCreateAccount.getAccountName().isEmpty()) { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000, 3, testKey002, - blockingStubFull)); - //Assert.assertTrue(sendCoin2(lowBalAddress, 1L, fromAddress, testKey002)); - GrpcAPI.Return ret1 = sendCoin2(lowBalAddress, 1000000L, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //Assert.assertTrue(Sendcoin(Low_Bal_ADDRESS, 1000000L, fromAddress, testKey002)); - noCreateAccount = queryAccount(lowBalTest, blockingStubFull); - logger.info(Long.toString(noCreateAccount.getBalance())); - //Assert.assertTrue(noCreateAccount.getBalance() == 1); - - //TestVoteToNonWitnessAccount - String voteStr = Base58.encode58Check(lowBalAddress); - - HashMap voteToNonWitnessAccount = new HashMap(); - voteToNonWitnessAccount.put(voteStr, "3"); - - HashMap voteToInvaildAddress = new HashMap(); - voteToInvaildAddress.put("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48SS", "4"); - - //TQkJsN2Q2sZV9H2dQ5x2rSneKNyLQgegVv - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - String createUrl1 = "adfafds"; - byte[] createUrl = createUrl1.getBytes(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ret1 = createWitness2(lowBalAddress2, createUrl, lowBalTest2); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - String voteStr1 = Base58.encode58Check(lowBalAddress2); - HashMap voteToWitAddress = new HashMap(); - voteToWitAddress.put(voteStr1, "1"); - PublicMethed.printAddress(lowBalTest); - ret1 = voteWitness2(voteToWitAddress, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //logger.info("vote to non witness account ok!!!"); - } - - //normal freezeBalance - //Assert.assertTrue(freezeBalance2(fromAddress, 10000000L, 3L, testKey002)) - ret1 = freezeBalance2(fromAddress, 100000000L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //vote To NonWitnessAccount - ret1 = voteWitness2(voteToNonWitnessAccount, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - //vote to InvaildAddress - ret1 = voteWitness2(voteToInvaildAddress, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : VoteNumber must more than 0"); - - } else { - logger.info( - "Please confirm wither the create account test is pass, or you will do it by manual"); - } - } - - @Test(enabled = true) - public void testUpdateAccount2() { - Account tryToUpdateAccount = queryAccount(lowBalTest, blockingStubFull); - if (tryToUpdateAccount.getAccountName().isEmpty()) { - GrpcAPI.Return ret1 = updateAccount2(lowBalAddress, mostLongNamePlusOneChar.getBytes(), - lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid accountName"); - - ret1 = updateAccount2(lowBalAddress, "".getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - System.out.println("dingwei2:"); - ret1 = updateAccount2(lowBalAddress, mostLongName.getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - ret1 = updateAccount2(lowBalAddress, "secondUpdateName".getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - } - } - - @Test(enabled = true) - public void testNoBalanceCreateAssetIssue2() { - Account lowaccount = queryAccount(lowBalTest, blockingStubFull); - if (lowaccount.getBalance() > 0) { - Assert.assertTrue(sendCoin(toAddress, lowaccount.getBalance(), lowBalAddress, lowBalTest)); - } - - System.out.println("1111112222"); - GrpcAPI.Return ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, TotalSupply, 1, 1, - now + 100000000L, now + 10000000000L, 2, description, url, 10000L, - 10000L, 1L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No enough balance for fee!"); - logger.info("nobalancecreateassetissue"); - } - - @Test(enabled = true) - public void testNoBalanceTransferTrx2() { - //Send Coin failed when there is no enough balance. - Assert.assertFalse(sendCoin(toAddress, 100000000000000000L, lowBalAddress, lowBalTest)); - } - - @Test(enabled = true) - public void testNoBalanceCreateWitness2() { - //Apply to be super witness failed when no enough balance. - //Assert.assertFalse(createWitness2(lowBalAddress, fromAddress, lowBalTest)); - System.out.println("1111222333:" + lowBalAddress); - GrpcAPI.Return ret1 = createWitness2(lowBalAddress, fromAddress, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : balance < AccountUpgradeCost"); - - } - - @Test(enabled = true) - public void testNoFreezeBalanceToUnfreezeBalance2() { - //Unfreeze account failed when no freeze balance - Account noFreezeAccount = queryAccount(lowBalTest, blockingStubFull); - if (noFreezeAccount.getFrozenCount() == 0) { - GrpcAPI.Return ret1 = unFreezeBalance2(lowBalAddress, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : no frozenBalance(BANDWIDTH)"); - } else { - logger.info("This account has freeze balance, please test this case for manual"); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean sendCoin(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } - - /** - * constructor. - */ - - public GrpcAPI.Return sendCoin2(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(TotalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddress = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddress); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public GrpcAPI.Return updateAccount2(byte[] addressBytes, byte[] accountNameBytes, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - logger.info(name); - return response; - } - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder = - BalanceContract.UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public GrpcAPI.Return unFreezeBalance2(byte[] address, String priKey) { - //byte[] address = address; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder = - BalanceContract.UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - return false; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - - public GrpcAPI.Return voteWitness2(HashMap witness, byte[] address, - String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .voteWitnessAccount2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - return response.getResult(); - - - } - - /** - * constructor. - */ - - public GrpcAPI.Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return response; - } - return ret; - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } - - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java deleted file mode 100644 index d394c879416..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java +++ /dev/null @@ -1,467 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class UpdateAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswe" - + "dcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static String name = "testAssetIssue010_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - String updateDescription = "This is test for update asset issue, case AssetIssue_010"; - String updateUrl = "www.updateassetissue.010.cn"; - Long freeAssetNetLimit = 1000L; - Long publicFreeAssetNetLimit = 1000L; - Long updateFreeAssetNetLimit = 10001L; - Long updatePublicFreeAssetNetLimit = 10001L; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset010Address = ecKey.getAddress(); - String testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true) - public void testUpdateAssetIssue2() { - //Sendcoin to this account - ByteString addressBS1 = ByteString.copyFrom(asset010Address); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - //Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,10000000L,3, - // testKey002,blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(asset010Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalance(asset010Address, 200000000L, 3, testKeyForAssetIssue010, - blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(asset010Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 1L, 1L, testKeyForAssetIssue010, blockingStubFull)); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, description.getBytes(), url.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - } - - //Query the description and url,freeAssetNetLimit and publicFreeAssetNetLimit - ByteString assetNameBs = ByteString.copyFrom(name.getBytes()); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueContractOuterClass.AssetIssueContract assetIssueByName = blockingStubFull - .getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(description)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(url)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - - //Test update asset issue - Return ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - updatePublicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //After update asset issue ,query the description and url, - // freeAssetNetLimit and publicFreeAssetNetLimit - assetNameBs = ByteString.copyFrom(name.getBytes()); - request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(updateDescription)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(updateUrl)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == updateFreeAssetNetLimit); - Assert - .assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == updatePublicFreeAssetNetLimit); - } - - @Test(enabled = true) - public void testUpdateAssetIssueExcption2() { - //Test update asset issue for wrong parameter - //publicFreeAssetNetLimit is -1 - Return ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - -1L, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid PublicFreeAssetNetLimit"); - //publicFreeAssetNetLimit is 0 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - 0, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //FreeAssetNetLimit is -1 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), -1, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid FreeAssetNetLimit"); - //FreeAssetNetLimit is 0 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), 0, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Description is null - ret1 = PublicMethed - .updateAsset2(asset010Address, "".getBytes(), updateUrl.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Url is null - ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), "".getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //Too long discription - ret1 = PublicMethed - .updateAsset2(asset010Address, tooLongDescription.getBytes(), url.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid description"); - //Too long URL - ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), tooLongUrl.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - Return ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), url.getBytes(), 1999999999, - 199, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = PublicMethed.queryAccount(priKey, blockingStubFull); - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.UnfreezeAssetContract.Builder builder = - AssetIssueContractOuterClass.UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - AssetIssueContractOuterClass.UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java deleted file mode 100644 index 4219adfeb37..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java +++ /dev/null @@ -1,585 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class VoteWitnessAccount2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test(enabled = true) - public void testVoteWitness2() { - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - //sendcoin - Return ret1 = PublicMethed.sendcoin2(lowBalAddress, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //assetissue - String createUrl1 = "adfafds"; - byte[] createUrl = createUrl1.getBytes(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - String voteStr1 = Base58.encode58Check(lowBalAddress); - - //Base58.encode58Check(getFinalAddress(key); - //String voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - String voteStr = voteStr1; - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - HashMap wrongVoteMap = new HashMap(); - wrongVoteMap.put(voteStr, "-1"); - HashMap zeroVoteMap = new HashMap(); - zeroVoteMap.put(voteStr, "0"); - - HashMap veryLargeMap = new HashMap(); - veryLargeMap.put(voteStr, "1000000000"); - HashMap wrongDropMap = new HashMap(); - wrongDropMap.put(voteStr, "10000000000000000"); - - //Vote failed due to no freeze balance. - //Assert.assertFalse(VoteWitness(smallVoteMap, NO_FROZEN_ADDRESS, no_frozen_balance_testKey)); - - //Freeze balance to get vote ability. - ret1 = PublicMethed.freezeBalance2(fromAddress, 10000000L, 3L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Vote failed when the vote is large than the freeze balance. - ret1 = voteWitness2(veryLargeMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - - //Vote failed due to 0 vote. - ret1 = voteWitness2(zeroVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : vote count must be greater than 0"); - - ret1 = voteWitness2(wrongVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : vote count must be greater than 0"); - - ret1 = voteWitness2(wrongDropMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : overflow: checkedMultiply(10000000000000000, 1000000)"); - ret1 = voteWitness2(smallVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - String value = witness.get(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - long count = Long.parseLong(value); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - - } - - /** - * constructor. - */ - - public Return voteWitness2(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - String value = witness.get(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - long count = Long.parseLong(value); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - //Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .voteWitnessAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return ret; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java deleted file mode 100644 index 6c31c38c336..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java +++ /dev/null @@ -1,308 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WithdrawBalance2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final String notWitnessTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] notWitness = PublicMethed.getFinalAddress(notWitnessTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test - public void testWithdrawBalance2() { - //Withdraw failed when you are not witness - Return ret1 = withdrawBalance2(notWitness, notWitnessTestKey); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "Account[41688b08971e740d7cecfa5d768f2787c1bb4c1268] is not a witnessAccount"); - - //Withdraw failed when the latest time to withdraw within 1 day. - ret1 = withdrawBalance2(fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - " Contract validate error : witnessAccount does not have any allowance"); - } - - /** - * constructor. - */ - - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - } - - /** - * constructor. - */ - - public Return withdrawBalance2(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.withdrawBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - ECKey ecKey = temKey; - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return response; - } - logger.info("test withdraw" + priKey); - return ret; - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - return false; - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - if (key.equals(afterVote.getVotes(j).getVoteAddress())) { - Long afterVoteNum = Long.parseLong(witness.get(key)); - Assert.assertTrue(afterVoteNum == afterVote.getVotes(j).getVoteCount()); - logger.info("test equal vote"); - } - } - } - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java deleted file mode 100644 index 837e4c72aa8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java +++ /dev/null @@ -1,757 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.util.EntityUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.SignUtils; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class ContractEvent001 extends JsonRpcBase { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] event002Address = ecKey2.getAddress(); - String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - // byte[] contractAddress = null; - String param = "10"; - static HttpResponse response; - static JSONObject responseContent; - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - private String fullnode1 = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - - - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void test1ContractEventAndLog() { - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - ecKey2 = new ECKey(Utils.getRandom()); - event002Address = ecKey2.getAddress(); - event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - AccountResourceMessage accountResource = - PublicMethed.getAccountResource(event001Address, blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(event001Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String contractName = "addressDemo"; - String code = - Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog1"); - byte[] contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - Integer i = 0; - for (i = 0; i < 1; i++) { - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventCycle(uint256)", - "100", - false, - 1L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLogCycle(uint256)", - "100", - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerUintEvent()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerintEvent()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventAndLog()", - "#", - false, - 1, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventNoIndex()", - "#", - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLog()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventNoIndex()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventOneIndex()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventTwoIndex()", - "#", - false, - 2L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEvent()", - "#", - false, - 3L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventCycle(uint256)", - "100", - false, - 1L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLogCycle(uint256)", - "100", - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForAnonymousHasLog()", - "#", - false, - 4L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForAnonymousNoLog()", - "#", - false, - 5L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - String param = "\"" + code + "\"" + "," + "\"" + code + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEvent(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - param = "\"" + "true1" + "\"" + "," + "\"" + "false1" + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerBoolEvent(bool,bool)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - String filename = "/Users/wangzihe/Documents/modify_fullnode/java-tron/tooLongString.txt"; - try { - FileReader fr = new FileReader(filename); - InputStreamReader read = new InputStreamReader(new FileInputStream(new File(filename))); - BufferedReader reader = new BufferedReader(read); - String tooLongString = reader.readLine(); - param = "\"" + tooLongString + "\"" + "," + "\"" + tooLongString + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEventAnonymous(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEvent(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - contractName = "addressDemo"; - code = Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog2"); - abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog2"); - contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerEventBytes()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - } - - @Test( - enabled = true, - threadPoolSize = 5, - invocationCount = 5, - description = "test eth_getFilterChanges") - public void testEthGetFilterChanges() throws InterruptedException { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - logger.info("event001Address:" + event001Address); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] event002Address = ecKey2.getAddress(); - logger.info("event002Address:" + event002Address); - String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - String contractName = "SolidityTest"; - String filePath = "./src/test/resources/soliditycode/testGetFilterChange.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - logger.info("11111111111111111111111111111111111"); - Thread.sleep(180000); - - long txidNum = 0; - HttpResponse response = getNowBlock(httpFullNode); - JSONObject responseContent = parseResponseContent(response); - long blockBefore = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blockBefore:" + blockBefore); - Thread.sleep(180000); - for (int i = 0; i < 5000; i++) { - String txid = - PublicMethed.triggerContract( - contractAddress, - "getResult(uint256)", - param, - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info("txid:" + txid); - txidNum++; - } - Thread.sleep(180000); - response = getNowBlock(httpFullNode); - responseContent = parseResponseContent(response); - long blockAfter = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - - logger.info("txidNum:" + txidNum); - - // 扫块 - long sumLogs = 0; - long totalTransactionsSize = 0; - logger.info("blockBefore:" + blockBefore); - logger.info("blockAfter:" + blockAfter); - for (long i = blockBefore; i <= blockAfter; i++) { - - response = getTransactionCountByBlocknum(httpFullNode, (int) i); - responseContent = parseResponseContent(response); - long transactionsSize = responseContent.getLong("count"); - - totalTransactionsSize += transactionsSize; - } - logger.info( - (int) (Thread.currentThread().getId()) - + "sumLogs:" - + totalTransactionsSize * Long.parseLong(param)); - } - - public static String[] arr = - new String[] { - "00", - "0x6b5c9c34aae469576dfcde3655c9036d", - "0x450de4565abf4434d66948fb2a568608", - "0x02a65b2cc37d2d34808a63b50b86e0cd", - "0x7474d244cecf3a943bf8ac6dbd7d60fa", - "0x4ab110c02b04d7781f774eeffa6432a3" - }; - - @Test( - enabled = true, - threadPoolSize = 5, - invocationCount = 5, - description = "Eth api of eth_getFilterChanges .") - public void test09GetFilterChanges() { - long sumSize = 0; - while (true) { - JsonArray params = new JsonArray(); - String id = arr[(int) (Thread.currentThread().getId()) - 16]; - params.add(id); - JsonObject requestBody = getJsonRpcBody("eth_getFilterChanges", params); - HttpResponse response = getJsonRpc(jsonRpcNode, requestBody); - JSONObject responseContent = parseResponseContent(response); - long size = responseContent.getJSONArray("result").size(); - sumSize += size; - logger.info(Thread.currentThread().getId() + ":sumSize:" + sumSize); - } - } - - /** constructor. */ - public static JSONObject parseResponseContent(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - JSONObject obj = JSONObject.parseObject(result); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /* public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - }*/ - - /** constructor. */ - public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { - HttpResponse response; - try { - - String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - public static HttpResponse getNowBlock(String httpNode) { - return getNowBlock(httpNode, false); - } - - /** constructor. */ - public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - - HttpResponse response; - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse createConnect(String url, JsonObject requestBody) { - HttpResponse response; - HttpPost httppost; - HttpClient httpClient; - Integer connectionTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); - Integer soTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); - PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); - pccm.setDefaultMaxPerRoute(80); - pccm.setMaxTotal(100); - - httpClient = new DefaultHttpClient(pccm); - try { - - httpClient - .getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - HttpResponse response; - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - return response; - } - - @Test(enabled = true, description = "Subscribe event client") - public void testEnergyCostDetail() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("blockTrigger"); - req.subscribe("transactionTrigger"); - req.subscribe("contractLogTrigger"); - req.subscribe("contractEventTrigger"); - req.monitor("inproc://reqmoniter", ZMQ.EVENT_CONNECTED | ZMQ.EVENT_DISCONNECTED); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect("tcp://47.94.197.215:55555"); - req.setReceiveTimeOut(10000); - - while (true) { - byte[] message = req.recv(); - if (message != null) { - System.out.println("receive : " + new String(message)); - } - } - } - - @Test(enabled = true) - public void testSingForHex() { - try { - SignInterface cryptoEngine = - SignUtils.fromPrivate( - ByteArray.fromHexString( - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"), - true); - /* ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(DBConfig.isECKeyCryptoEngine(), - ByteArray.fromHexString( - "ba989430c392dedef66a259a1f1112b178dbe7f2793975d8cf80f9b31ecd33ff")) - .getBytes())));*/ - // - ByteString sig = - ByteString.copyFrom( - cryptoEngine.Base64toBytes( - cryptoEngine.signHash( - ByteArray.fromHexString( - "4f2a4c136f56a41714b42e14d497e38dcbe0f9c4ca2e5957cf3a340c62d133f8")))); - logger.info(ByteArray.toHexString(sig.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java b/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java deleted file mode 100644 index 6da00b39793..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java +++ /dev/null @@ -1,253 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class CycleMultiSign { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidityInFullnode = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - private ECKey ecKey = new ECKey(Utils.getRandom()); - private byte[] test001Address = ecKey.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - //(use no id) - @Test(enabled = true) - public void testMultiSignActiveAddress() { - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, 10000000000000L, fromAddress, testKey002, - blockingStubFull)); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - logger.info("wei-----------------------"); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}]} "; - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - logger.info("1-----------------------"); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String accountPermissionJson3 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - String accountPermissionJson4 = "{\"owner_permission\":{\"type\":0,\"" - + "permission_name\":\"owner\",\"threshold\":1,\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\",\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]},{\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]},{\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\",\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\",\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0020000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - while (true) { - PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, - dev001Key, - blockingStubFull, 0, - permissionKeyString); - addressPermission(dev001Key, accountPermissionJson2); - addressPermission(dev001Key, accountPermissionJson3); - addressPermission(dev001Key, accountPermissionJson4); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - } - } - - /** - * constructor. - */ - - public void addressPermission(String addKey, String accountPermissionJson) { - PublicMethed.freezeBalanceForReceiver(test001Address, - 10000000L, 0, 0, - com.google.protobuf.ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = addKey; - PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - test001Address, blockingStubFull); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java deleted file mode 100644 index 967067b46a6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java +++ /dev/null @@ -1,340 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -//import org.tron.protos.Protocol.DeferredTransaction; - -@Slf4j -public class DelayTransactionStress { - - public static final long MAX_DEFERRED_TRANSACTION_DELAY_SECONDS = 45 * 24 * 3_600L; //45 days - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional infoById = null; - //Optional deferredTransactionById = null; - Optional getTransactionById = null; - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] delayAccount1Address = ecKey.getAddress(); - String delayAccount1Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] receiverAccountAddress = ecKey3.getAddress(); - String receiverAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] delayAccount3Address = ecKey4.getAddress(); - String delayAccount3Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] receiverAccount4Address = ecKey5.getAddress(); - String receiverAccount4Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private Long delayTransactionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.delayTransactionFee"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 2000) - public void test1DelaySendcoinStress() { - String txid = ""; - Integer i = 0; - String cancelId = ""; - while (i++ <= 10000000) { - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - txid = PublicMethed.sendcoinDelayedGetTxid(delayAccount2Address, 1L, 20, fromAddress, - testKey002, blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - if (i % 20 == 0) { - cancelId = txid; - //PublicMethed.sendcoin(delayAccount2Address,1L,fromAddress,testKey002,blockingStubFull); - } - if (i % 39 == 0) { - PublicMethed.cancelDeferredTransactionById(cancelId, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(delayAccount2Address, 1L, fromAddress, testKey002, - blockingStubFull); - } - - } - - - } - - /* @Test(enabled = true, description = "Get deferred transaction by id") - public void test2getDeferredTransactionByid() { - //get account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - receiverAccountAddress = ecKey3.getAddress(); - receiverAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(delayAccount2Key); - PublicMethed.printAddress(receiverAccountKey); - - //Pre sendcoin to the test account - Assert.assertTrue(PublicMethed.sendcoin(delayAccount2Address, 100000000L,fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(receiverAccountAddress, 10L,fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Do delay send coin transaction. - Long delaySecond = 10L; - Long sendCoinAmout = 100L; - - //Query balance before send coin. - Long deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - String txid = PublicMethed.sendcoinDelayedGetTxid(receiverAccountAddress, sendCoinAmout, - delaySecond,delayAccount2Address, - delayAccount2Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance when pre-sendcoin stage. - Long deplayAccountInDelayBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountInDelayalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountInDelayBalance " + deplayAccountInDelayBalance); - logger.info("recevierAccountInDelayalance " + recevierAccountInDelayalance); - Assert.assertTrue(recevierAccountBeforeBalance == recevierAccountInDelayalance); - //Assert.assertTrue(); - - - deferredTransactionById = PublicMethed.getDeferredTransactionById(txid,blockingStubFull); - DeferredTransaction transaction = deferredTransactionById.get(); - String finalTxid = ByteArray.toHexString(Sha256Hash.hash(transaction.getTransaction() - .getRawData().toByteArray())); - PublicMethed.getDeferredTransactionById(finalTxid,blockingStubFull); - logger.info(finalTxid); - //logger.info("receiver address is " + Base58.encode58Check(transaction - .getReceiverAddress().toByteArray())); - Assert.assertTrue(Base58.encode58Check(transaction.getReceiverAddress().toByteArray()) - .equalsIgnoreCase(PublicMethed.getAddressString(receiverAccountKey))); - //logger.info("sender address is " + Base58.encode58Check(transaction - .getSenderAddress().toByteArray())); - Assert.assertTrue(Base58.encode58Check(transaction.getSenderAddress().toByteArray()) - .equalsIgnoreCase(PublicMethed.getAddressString(delayAccount2Key))); - // logger.info("delaySeconds is " + transaction.getDelaySeconds()); - Assert.assertTrue(delaySecond == transaction.getDelaySeconds()); - //logger.info("DelayUntil " + transaction.getDelayUntil()); - Assert.assertTrue(transaction.getDelayUntil() > System.currentTimeMillis()); - //logger.info("Expiration " + transaction.getExpiration()); - Assert.assertTrue(transaction.getExpiration() > System.currentTimeMillis()); - //logger.info("PublishTime " + transaction.getPublishTime()); - Assert.assertTrue(transaction.getPublishTime() < System.currentTimeMillis()); - //Assert.assertTrue(transaction.getDelayUntil() + 60000 == transaction.getExpiration()); - getTransactionById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("transaction stage in txid is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - - Assert.assertTrue(getTransactionById.get().getRawData().getDeferredStage().getStage() == 1); - getTransactionById = PublicMethed.getTransactionById(finalTxid, blockingStubFull); - logger.info("transaction stage in final id is " + getTransactionById - .get().getRawData().getDeferredStage().getStage()); - Assert.assertTrue(getTransactionById.get().getRawData().getDeferredStage().getStage() == 0); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.getDeferredTransactionById(finalTxid,blockingStubFull); - deferredTransactionById = PublicMethed.getDeferredTransactionById(txid,blockingStubFull); - finalTxid = ByteArray.toHexString(Sha256Hash.hash(transaction.getTransaction() - .getRawData().toByteArray())); - transaction = deferredTransactionById.get(); - logger.info(finalTxid); - //logger.info("receiver address is " + Base58.encode58Check(transaction.getReceiverAddress() - .toByteArray())); - //logger.info("receiver address is " + Base58.encode58Check(transaction.getSenderAddress() - .toByteArray())); - //logger.info("delaySeconds is " + transaction.getDelaySeconds()); - //logger.info("DelayUntil " + transaction.getDelayUntil()); - //logger.info("Expiration " + transaction.getExpiration()); - //logger.info("PublishTime " + transaction.getPublishTime()); - getTransactionById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("transaction stage in txid is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - getTransactionById = PublicMethed.getTransactionById(finalTxid, blockingStubFull); - logger.info("transaction stage in final id is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - - - - //Query balance after delay send coin. - Long deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(deplayAccountBeforeBalance - deplayAccountAfterBalance == sendCoinAmout - + 100000L); - Assert.assertTrue(recevierAccountAfterDelayalance - recevierAccountBeforeBalance - == sendCoinAmout); - - }*/ - - @Test(enabled = true, description = "Delay send coin") - public void test3DelaySendCoin() { - ecKey4 = new ECKey(Utils.getRandom()); - delayAccount3Address = ecKey4.getAddress(); - delayAccount3Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - PublicMethed.printAddress(delayAccount3Key); - - ecKey5 = new ECKey(Utils.getRandom()); - receiverAccount4Address = ecKey5.getAddress(); - receiverAccount4Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - PublicMethed.printAddress(receiverAccount4Key); - - Long sendCoinAmount = 100000000L; - //Pre sendcoin to the test account - Assert.assertTrue(PublicMethed.sendcoin(delayAccount3Address, sendCoinAmount, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Do delay send coin transaction. - logger.info("----------------No balance to send coin--------------------"); - //Test no balance to send coin. - //Query balance before send coin. - Long deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - Long recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Long delaySecond = 4L; - Assert.assertFalse(PublicMethed.sendcoinDelayed(receiverAccount4Address, sendCoinAmount, - delaySecond, delayAccount3Address, delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - Long deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - Long recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(recevierAccountAfterDelayalance == 0); - logger.info("deplayAccountBeforeBalance: " + deplayAccountBeforeBalance); - logger.info("deplayAccountAfterBalance: " + deplayAccountAfterBalance); - - Assert.assertEquals(deplayAccountBeforeBalance, deplayAccountAfterBalance); - - logger.info("----------------No balance to create account send coin--------------------"); - //Test delay send coin to create account. - deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Long createAccountFee = 100000L; - Assert.assertTrue(PublicMethed.sendcoinDelayed(receiverAccount4Address, - deplayAccountBeforeBalance - createAccountFee, delaySecond, delayAccount3Address, - delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, blockingStubFull) - .getBalance(); - recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(recevierAccountAfterDelayalance == 0); - Assert.assertTrue(deplayAccountBeforeBalance - deplayAccountAfterBalance == 100000); - - logger.info("---------------Balance enough to create account send coin--------------------"); - //Test delay send coin to create account. - createAccountFee = 100000L; - deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Assert.assertTrue(PublicMethed.sendcoinDelayed(receiverAccount4Address, - deplayAccountBeforeBalance - createAccountFee - delayTransactionFee, - delaySecond, delayAccount3Address, delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - Long receiverBalanceShouldBe = deplayAccountBeforeBalance - createAccountFee - - delayTransactionFee; - - Assert.assertEquals(recevierAccountAfterDelayalance, receiverBalanceShouldBe); - Assert.assertTrue(deplayAccountAfterBalance == 0); - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java deleted file mode 100644 index 8c4dab36742..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java +++ /dev/null @@ -1,619 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashStressTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2); - private AtomicLong count = new AtomicLong(); - private AtomicLong errorCount = new AtomicLong(); - private long startTime = System.currentTimeMillis(); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] extCodeHashContractAddress = null; - private byte[] normalContractAddress = null; - private byte[] testContractAddress = null; - private byte[] dev001Address = fromAddress; - private String dev001Key = testKey002; - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy a normal contract to be used for stress testing.") - public void test01DeployNormalContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashStress.sol"; - String contractName = "TriggerNormal"; //TBVEkA72g1wFoBBVLSXFZ2Bp944oL17NeU - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - normalContractAddress = deployContract(code, abi, contractName, blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(normalContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Deploy a extcodehash contract.") - public void test02DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashStress.sol"; - String contractName = "Trigger"; //THAx2PcAtRCerwrLGN237dahqSUfq5wLnR - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - extCodeHashContractAddress = deployContract(code, abi, contractName, blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - /** - * trigger. - */ - public byte[] deployContract(String bytecode, String abi, String contractName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, bytecode, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - return infoById.get().getContractAddress().toByteArray(); - } - - /** - * trigger. - */ - public String triggerContractWithMaxFeeLimit(byte[] testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit) { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "test(address)", param, false, callValue, - maxFeeLimit, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger - .info("transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - - if (infoById.get().getResMessage().toStringUtf8().toLowerCase().contains("cpu")) { - throw new IllegalArgumentException(); - } - if (infoById.get().getResMessage().toStringUtf8().toLowerCase().contains("timeout")) { - throw new IllegalArgumentException(); - } - return "ok"; - } - - /** - * trigger. - */ - public String triggerAndGetExtCodeHashList(List testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit, WalletGrpc.WalletBlockingStub blockingStubFull) { - - Long callValue = Long.valueOf(0); - List params = new ArrayList<>(); - for (int i = 0; i < testAddress.size(); i++) { - params.add(Base58.encode58Check(testAddress.get(i))); - } - final String triggerTxid = PublicMethed.triggerParamListContract(extCodeHashContractAddress, - "test(address[])", Arrays.asList(params), false, callValue, - maxFeeLimit, "0", 0, user001Address, user001Key, - blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger - .info( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - - return "ok"; - - } - - /** - * trigger. - */ - public void triggerAndGetExtCodeHash(byte[] testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit, WalletGrpc.WalletBlockingStub blockingStubFull) { - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(normalContractAddress, - "test(address)", param, false, callValue, - 314982000, "0", 0, user001Address, user001Key, - blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger - .info( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - private synchronized void wirteLine(String fileName, String line) { - try { - BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); - out.write(line); - out.newLine(); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test(enabled = true, description = "Deploy multiple long bytecode contract " - + "and write address to file.") - public void test03DeployMultiLongByteCodeContract() { - - ExecutorService pool = Executors.newFixedThreadPool(30); - Map addressMap = new ConcurrentHashMap<>(); - int size = 50_0_000; - int stubSize = 30; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - CountDownLatch count = new CountDownLatch(size); - for (int i = 0; i < size; i++) { - - String contractName = "extcodehashContract" + i; - logger.info("[" + i + "]contractName: " + contractName); - pool.submit(new DeployTask(addressMap, i, count, stubs.get(i % stubSize))); - - } - - try { - count.await(); - for (String s : addressMap.keySet()) { - System.out.println(s); - } - - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Test(enabled = true, description = "Calculate the contract maxfeelimit.", - threadPoolSize = 1, invocationCount = 1) - public void test04StressGetExtCodeHashContract() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - extCodeHashContractAddress = WalletClient - .decodeFromBase58Check("TEsdDpJQrLBDPmJfDF2Ex53iMfzetqHvn9"); - - // long bytecode contract - testContractAddress = WalletClient.decodeFromBase58Check("TDqSAv8gLFXQRfug5Pr1Ev6zrEj1efC8qe"); - - HashMap retMap = new HashMap<>(); - - long feeLimit = 314982000; - // long feeLimit = 393624800; - // long feeLimit = 406731800; - - long base = 100; - long lastSuccess = feeLimit; - int failed = 0; - - for (int i = 0; i < 1000000000; i++) { - try { - String retCode = triggerContractWithMaxFeeLimit(testContractAddress, user001Address, - user001Key, - feeLimit); - logger.info("[" + i + "]retCode: " + retCode); - logger.info("[" + i + "]feeLimit: " + feeLimit); - lastSuccess = feeLimit; - base *= 2; - feeLimit += base; - failed = 0; - } catch (Exception e) { - failed++; - if (failed > 3) { - break; - } - logger.error("cpu timeout"); - feeLimit = lastSuccess; - base = 100; - } - } - } - - @Test(enabled = true, description = "Trigger extcodeHash contract stress.") - public void test05TriggerContract() throws FileNotFoundException { - - BufferedReader reader = null; - List addresses = new ArrayList<>(); - try { - reader = new BufferedReader(new FileReader("src/test/resources/address2")); - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - // read next line - line = reader.readLine(); - addresses.add(line); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - ExecutorService pool = Executors.newFixedThreadPool(50); - int stubSize = 50; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - int paramsSize = 75; // the address count per trigger - int trigger = 0; - for (int i = 0; i + paramsSize < addresses.size(); i += paramsSize) { - System.err.println(trigger++); - System.err.println(i + " " + (i + paramsSize)); - pool.submit(new TriggerTask(addresses.subList(i, i + paramsSize), stubs.get( - (int) (Math.random() * 100 % stubSize)))); - } - - try { - Thread.sleep(100000000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * trigger. - */ - public void triggerContact(String[] testList, WalletGrpc.WalletBlockingStub stub) { - - final byte[] user001Address = fromAddress; - final String user001Key = testKey002; - - extCodeHashContractAddress = WalletClient - .decodeFromBase58Check("TJGYcUspHrwPgy72YeaVjD4Skep9Ji8Pnn"); - - final long feeLimit = 102471600; - count.getAndAdd(1); - if (count.get() % 100 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - - List addressList = new ArrayList<>(); - - for (int k = 0; k < testList.length; k++) { - addressList.add(WalletClient.decodeFromBase58Check(testList[k])); - } - triggerAndGetExtCodeHashList(addressList, user001Address, user001Key, feeLimit, stub); - } - - @Test(enabled = true, description = "Trigger normal contract stress.") - public void test06TriggerNormalContract() throws FileNotFoundException { - - BufferedReader reader = null; - List addresses = new ArrayList<>(); - try { - reader = new BufferedReader(new FileReader( - "src/test/resources/address2")); - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - // read next line - line = reader.readLine(); - addresses.add(line); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - ExecutorService pool = Executors.newFixedThreadPool(50); - int stubSize = 50; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - int paramsSize = 50; - int trigger = 0; - for (int i = 0; i + paramsSize < addresses.size(); i += 1) { - System.err.println(trigger++); - System.err.println(i + " " + (i + paramsSize)); - pool.submit( - new TriggerNormalTask(addresses.subList(0, 0 + paramsSize), stubs.get( - (int) (Math.random() * 100 % stubSize)))); - } - - try { - Thread.sleep(100000000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * trigger. - */ - public void triggerNormalContact(String[] testList, WalletGrpc.WalletBlockingStub stub) { - - final byte[] user001Address = fromAddress; - final String user001Key = testKey002; - - normalContractAddress = WalletClient - .decodeFromBase58Check("TFUSarvJtCSQhDifdRaioytThohLSLCjq4"); - - final long feeLimit = 51079600; - count.getAndAdd(1); - if (count.get() % 100 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - - List addressList = new ArrayList<>(); - - for (int k = 0; k < testList.length; k++) { - addressList.add(WalletClient.decodeFromBase58Check(testList[k])); - } - - triggerAndGetExtCodeHash(normalContractAddress, user001Address, - user001Key, feeLimit, stub); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - class DeployTask implements Runnable { - - Map addressList; - CountDownLatch countDownLatch; - WalletGrpc.WalletBlockingStub stub; - int index; - - DeployTask(Map addressList, int index, CountDownLatch countDownLatch, - WalletGrpc.WalletBlockingStub stub) { - this.index = index; - this.addressList = addressList; - this.countDownLatch = countDownLatch; - this.stub = stub; - } - - @Override - public void run() { - logger.info("depoying :" + index); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_veryLarge"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_veryLarge"); - try { - byte[] deployedAddress = deployContract(code, abi, "test" + index, stub); - String address = Base58.encode58Check(deployedAddress); - wirteLine( - "src/test/resources/addresses2", - address); - logger.info("deployed : " + index + " " + address); - } catch (Throwable e) { - logger.error("deploy error: ", e); - } finally { - countDownLatch.countDown(); - } - } - } - - class CheckTask implements Runnable { - - String txid; - WalletGrpc.WalletBlockingStub client; - - CheckTask(String txid, WalletGrpc.WalletBlockingStub client) { - this.txid = txid; - this.client = client; - } - - @Override - public void run() { - - Optional infoById = PublicMethed - .getTransactionInfoById(this.txid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - if (infoById.get().getResultValue() != 0) { - logger.error("txid:" + this.txid); - logger.error( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - logger.info("infoById" + infoById); - } - } - - class TriggerTask implements Runnable { - - List addresses; - WalletGrpc.WalletBlockingStub stub; - - TriggerTask(List addresses, WalletGrpc.WalletBlockingStub stub) { - this.addresses = addresses; - this.stub = stub; - } - - @Override - public void run() { - triggerContact(this.addresses.toArray(new String[0]), stub); - } - } - - class TriggerNormalTask implements Runnable { - - List addresses; - WalletGrpc.WalletBlockingStub stub; - - TriggerNormalTask(List addresses, WalletGrpc.WalletBlockingStub stub) { - this.addresses = addresses; - this.stub = stub; - } - - @Override - public void run() { - triggerNormalContact(this.addresses.toArray(new String[0]), stub); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java deleted file mode 100644 index 7a1fd953fb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.CoreConnectionPNames; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpStressTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000000000L; - static Integer connectionTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpConnectionTimeout"); - static Integer soTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpSoTimeout"); - private static String name = "testAssetIssue002_" + Long.toString(now); - private static String assetIssueId1; - private static String assetIssueId2; - private static Integer exchangeId; - private static Long beforeInjectBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeOwnerAddress = ecKey1.getAddress(); - String exchangeOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset2Address = ecKey2.getAddress(); - String asset2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void test4InjectExchange() { - final long now = System.currentTimeMillis(); - final long totalSupply = 10000000000000000L; - Long beforeInjectBalance; - HttpClient httpClient = new DefaultHttpClient(); - HttpPost httppost; - httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, - connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - - response = HttpMethed - .sendCoin(httpnode, fromAddress, exchangeOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, exchangeOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, - 2, 3, description, url, 1000L, 1000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.assetIssue(httpnode, asset2Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, - 2, 3, description, url, 1000L, 1000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, exchangeOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, asset2Address); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - response = HttpMethed - .transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, - 100000000000000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create exchange. - response = HttpMethed.exchangeCreate(httpnode, exchangeOwnerAddress, assetIssueId1, - 50000000000000L, assetIssueId2, 50000000000000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.listExchanges(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - Integer times = 0; - while (times++ <= 10000) { - HttpMethed.sendCoin(httpnode, fromAddress, exchangeOwnerAddress, 100L, testKey002); - HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, 100L, testKey002); - //Inject exchange. - HttpMethed.exchangeInject(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 10L, exchangeOwnerKey); - HttpMethed.exchangeWithdraw(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 10L, exchangeOwnerKey); - HttpMethed.exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 100L, 1L, exchangeOwnerKey); - HttpMethed.exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId2, - 100L, 1L, exchangeOwnerKey); - HttpMethed.transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, - 1L, asset2Key); - HttpMethed.transferAsset(httpnode, exchangeOwnerAddress, asset2Address, assetIssueId1, - 1L, exchangeOwnerKey); - HttpMethed.participateAssetIssue(httpnode, exchangeOwnerAddress, asset2Address, - assetIssueId1, 1L, asset2Key); - HttpMethed.participateAssetIssue(httpnode, asset2Address, exchangeOwnerAddress, - assetIssueId2, 1L, exchangeOwnerKey); - HttpMethed.freezeBalance(httpnode, fromAddress, 10000000000L, 0, 0, - exchangeOwnerAddress, testKey002); - HttpMethed.freezeBalance(httpnode, fromAddress, 10000000000L, 0, 1, - exchangeOwnerAddress, testKey002); - HttpMethed.unFreezeBalance(httpnode, fromAddress, 0, exchangeOwnerAddress, testKey002); - HttpMethed.unFreezeBalance(httpnode, fromAddress, 1, exchangeOwnerAddress, testKey002); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java deleted file mode 100644 index b0f90198084..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MainNetTransferSendOrAsset { - - //testng001、testng002、testng003、testng004 - //fromAssetIssue - private final String testKey001 = - "BC70ADC5A0971BA3F7871FBB7249E345D84CE7E5458828BE1E28BF8F98F2795B"; - //toAssetIssue - private final String testKey002 = - "F153A0E1A65193846A3D48A091CD0335594C0A3D9817B3441390FDFF71684C84"; - //fromSend - private final String testKey003 = - "2514B1DD2942FF07F68C2DDC0EE791BC7FBE96FDD95E89B7B9BB3B4C4770FFAC"; - //toSend - private final String testKey004 = - "56244EE6B33C14C46704DFB67ED5D2BBCBED952EE46F1FD88A50C32C8C5C64CE"; - //Default - private final String defaultKey = - "8DFBB4513AECF779A0803C7CEBF2CDCC51585121FAB1E086465C4E0B40724AF1"; - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] fromSendAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] toSendAddress = PublicMethed.getFinalAddress(testKey004); - private final byte[] defaultAddress = PublicMethed.getFinalAddress(defaultKey); - - - private final Long transferAmount = 1L; - private final Long sendAmount = 1L; - private Long start; - private Long end; - private Long beforeToBalance; - private Long afterToBalance; - private Long beforeToAssetBalance = 0L; - private Long afterToAssetBalance = 0L; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - if (fromAccount.getBalance() < 10000000000L) { - PublicMethed - .sendcoin(fromAddress, 10000000000L, defaultAddress, defaultKey, blockingStubFull); - } - if (fromAccount.getAssetCount() == 0) { - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - PublicMethed.createAssetIssue(fromAddress, "testNetAsset", 1000000000000L, - 1, 1, start, end, 1, "wwwwww", "wwwwwwww", 100000L, - 100000L, 1L, 1L, testKey001, blockingStubFull); - } - beforeToBalance = toAccount.getBalance(); - beforeToAssetBalance = toAccount.getAssetMap().get("testNetAsset"); - - Account fromSendAccount = PublicMethed.queryAccount(testKey003, blockingStubFull); - Account toSendAccount = PublicMethed.queryAccount(testKey004, blockingStubFull); - if (fromSendAccount.getBalance() < 1000000000L) { - PublicMethed - .sendcoin(fromSendAddress, 1000000000L, defaultAddress, defaultKey, blockingStubFull); - } - beforeToBalance = toAccount.getBalance(); - logger.info("Before From account balance is " + Long.toString(fromAccount.getBalance())); - logger.info("Before To account balance is " + Long.toString(toAccount.getBalance())); - start = System.currentTimeMillis(); - } - - @Test(enabled = false, threadPoolSize = 20, invocationCount = 100000) - public void freezeAnd() throws InterruptedException { - Random rand = new Random(); - Integer randNum = 0; - randNum = rand.nextInt(1000); - try { - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Integer i = 0; - while (i < 60) { - PublicMethed - .transferAsset(toAddress, "testNetAsset".getBytes(), transferAmount, fromAddress, - testKey001, blockingStubFull); - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - PublicMethed.sendcoin(toSendAddress, sendAmount, fromSendAddress, testKey003, - blockingStubFull); - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - end = System.currentTimeMillis(); - logger.info("Time is " + Long.toString(end - start)); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - afterToBalance = toAccount.getBalance(); - afterToAssetBalance = toAccount.getAssetMap().get("testNetAsset"); - - logger.info("Success times is " + Long.toString(afterToAssetBalance - beforeToAssetBalance)); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java deleted file mode 100644 index 93abe8957b9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java +++ /dev/null @@ -1,359 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class MainNetVoteOrFreezeOrCreate { - - private static final long now = System.currentTimeMillis(); - private static String name = "mainNetAsset_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - //Devaccount - private final String testKey001 = - "2514B1DD2942FF07F68C2DDC0EE791BC7FBE96FDD95E89B7B9BB3B4C4770FFAC"; - //Zion - private final String testKey002 = - "56244EE6B33C14C46704DFB67ED5D2BBCBED952EE46F1FD88A50C32C8C5C64CE"; - //Default - private final String defaultKey = - //Mainet - //"8DFBB4513AECF779A0803C7CEBF2CDCC51585121FAB1E086465C4E0B40724AF1"; - //Beta Env - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] defaultAddress = PublicMethed.getFinalAddress(defaultKey); - private final Long sendAmount = 1026000000L; - long totalSupply = now; - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "f"; - String url = "h"; - Long startTime; - Long endTime; - Boolean ret = false; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long start; - private Long end; - private Long beforeToBalance; - private Long afterToBalance; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - return true; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - startTime = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 2, invocationCount = 2) - public void freezeAndSendcoin() throws InterruptedException { - Random rand = new Random(); - Integer randNum = 0; - randNum = rand.nextInt(1000); - try { - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - Integer i = 0; - while (i++ < 3) { - ret = false; - Integer waitTime = 10; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountAddress = ecKey1.getAddress(); - String testKeyAccount = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - logger.info(Base58.encode58Check(accountAddress)); - logger.info(testKeyAccount); - Integer tryTimes = 0; - - while (!ret) { - ret = PublicMethed - .createAccount(defaultAddress, accountAddress, defaultKey, blockingStubFull); - logger.info("createAccount"); - - if (tryTimes++ == 10) { - break; - } - } - - ret = false; - while (!ret) { - ret = PublicMethed - .sendcoin(accountAddress, sendAmount, defaultAddress, defaultKey, blockingStubFull); - logger.info("sendcoin"); - } - ret = false; - while (!ret) { - name = "mainNetAsset_" + Long.toString(System.currentTimeMillis()); - totalSupply = System.currentTimeMillis(); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - ret = PublicMethed.createAssetIssue(accountAddress, name, totalSupply, 1, 1, start, end, - 1, description, url, 3000L, 3000L, 1L, 1L, - testKeyAccount, blockingStubFull); - logger.info("createAssetIssue"); - } - ret = false; - while (!ret) { - ret = freezeBalance(accountAddress, 1000000L, 3, testKeyAccount, - blockingStubFull); - logger.info("freezeBalance"); - } - /* ret = false; - while (!ret) { - ret = PublicMethed - .transferAsset(toAddress, name.getBytes(), 10L, accountAddress, testKeyAccount, - blockingStubFull); - logger.info("transferAsset"); - }*/ - ret = false; - while (!ret) { - String voteStr = Base58 - .encode58Check(result.get().getWitnesses(i % 5).getAddress().toByteArray()); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - ret = voteWitness(smallVoteMap, accountAddress, testKeyAccount); - logger.info("voteWitness"); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - endTime = System.currentTimeMillis(); - logger.info("Time is " + Long.toString(endTime - startTime)); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = WitnessContract - .VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address = " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - //logger.info("transaction == null,\n contract:{},\n transaction:{}" , contract.toString(), - // transaction.toString()); - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - //logger.info(response.getCode().toString()); - return false; - } - /* try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java deleted file mode 100644 index 58c07f830f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java +++ /dev/null @@ -1,336 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class MultiValiSignPerformanceTest { - - private final String fromKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(fromKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractDepAddress = ecKey1.getAddress(); - String contractDepKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private byte[] ecrecoverContractAddress = null; - private byte[] multiValiSignContractAddress = null; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractDepKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "deploy ecrecover contract") - public void test01DeployEcrecoverContract() { - Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(contractDepAddress, contractDepKey, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(contractDepAddress), fromKey, blockingStubFull)); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contractDepAddress, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "src/test/resources/soliditycode/multiValiSignPerformance01.sol"; - String contractName = "ecrecoverValidateSign"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractDepKey, - contractDepAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(contractDepAddress, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - ecrecoverContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("ecrecoverContractAddress:" + infoById.get().getContractAddress()); - SmartContract smartContract = PublicMethed.getContract(ecrecoverContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "deploy multvalisign contract") - public void test02DeployMultvalisignContract() { - Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(contractDepAddress, contractDepKey, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(contractDepAddress), fromKey, blockingStubFull)); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contractDepAddress, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "src/test/resources/soliditycode/multiValiSignPerformance02.sol"; - String contractName = "multiValidateSignContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractDepKey, - contractDepAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(contractDepAddress, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - multiValiSignContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("multiValiSignContractAddress:" + infoById.get().getContractAddress()); - SmartContract smartContract = PublicMethed.getContract(multiValiSignContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "trigger ecrecover contract test") - public void test03triggerEcrecoverContract() { - /*Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - try { - Thread.sleep(new Long(30000)); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = ByteArray - .fromHexString("7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e"); - logger.info("hash:" + Hex.toHexString(hash)); - int cnt = 15; - for (int i = 0; i < cnt; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - - String txid = ""; - long start = System.currentTimeMillis(); - txid = PublicMethed - .triggerContract(PublicMethed.decode58Check("TDgdUs1gmn1JoeGMqQGkkxE1pcMNSo8kFj"), - "validateSign(bytes32,bytes[],address[])", input, - false, 0, maxFeeLimit, contractDepAddress, contractDepKey, blockingStubFull); - long timeCosts = System.currentTimeMillis() - start; - logger.info( - "Ecrecover--cnt:" + cnt + ",timeCost:" + timeCosts + ",ms:" + (timeCosts * 1.0 / cnt)); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "trigger mulivalisign contract test") - public void test04triggerMuliValiSignContract() { - /*Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - try { - Thread.sleep(new Long(30000)); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - - byte[] hash = ByteArray - .fromHexString("7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e"); - logger.info("hash:" + Hex.toHexString(hash)); - int cnt = 15; - for (int i = 0; i < cnt; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - - String txid = ""; - long start = System.currentTimeMillis(); - txid = PublicMethed - .triggerContract(PublicMethed.decode58Check("TVpTLZbBbP82aufo7p3qmb4ELiowH3mjQW"), - "testArray(bytes32,bytes[],address[])", input, false, - 0, maxFeeLimit, contractDepAddress, contractDepKey, blockingStubFull); - long timeCosts = System.currentTimeMillis() - start; - logger.info( - "MuliValiSign--cnt:" + cnt + ",timeCost:" + timeCosts + ",ms:" + (timeCosts * 1.0 / cnt)); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java deleted file mode 100644 index 31516dc18d8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java +++ /dev/null @@ -1,143 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignStress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 20, invocationCount = 20) - public void testMutiSignForAccount() { - Integer i = 0; - while (i < 20) { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - accountPermissionJson = "[{\"keys\":[{\"address\":\"" - + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}],\"name\":\"owner\",\"threshold\":2,\"parent\":\"owner\"}," - + "{\"parent\":\"owner\",\"keys\":[{\"address\":\"" - + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1},{\"address\":\"" - + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}],\"name\":\"active\"," - + "\"threshold\":2}]"; - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - String updateName = Long.toString(System.currentTimeMillis()); - - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - } - - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java deleted file mode 100644 index a04dbc86262..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java +++ /dev/null @@ -1,1100 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.AccountResource; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.Sha256Sm3Hash; - -@Slf4j -public class ScanBlockTools { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = "39.106.110.245:50051"; - private String fullnode1 = "39.106.110.245:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - public static List listForTxid = new ArrayList<>(); - public static HashMap map = new HashMap<>(); - public static HashMap witnessMap = new HashMap<>(); - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void test01ScanTransaction() { - getTxidList(); - witnessMap.clear(); - map.clear(); - witnessMap.put(5,"41F08012B4881C320EB40B80F1228731898824E09D"); - witnessMap.put(10,"41DF309FEF25B311E7895562BD9E11AAB2A58816D2"); - witnessMap.put(15,"41BB7322198D273E39B940A5A4C955CB7199A0CDEE"); - witnessMap.put(20,"412080D8A0364E82150DD5235CE7A61A7B40F3F9EF"); - witnessMap.put(25,"4173FC381D3E2AFEFCCED94A57D49520291C38AFBB"); - witnessMap.put(30,"41AF6146B0AD9EE8BBEE811D5858F3252666DFC90C"); - witnessMap.put(35,"41AF6A9D9C0636BD9DF74F687B90C6F44C471A6AB3"); - witnessMap.put(40,"41AF730429E4AB7BF7B53FB15ACB1D45EF5B22F463"); - witnessMap.put(45,"41AF4AEA1C4CBCFA681D98C354C142938381C99389"); - witnessMap.put(50,"41AF53DC31D9DE64DFF59A847125EFCA89D97BC86D"); - witnessMap.put(55,"41AF49468FA1BA966244D76F7D0139FC2CA751FAA5"); - witnessMap.put(60,"41AF5360256F958D2A922D160C429F13D432EFC22F"); - witnessMap.put(65,"41AF5EF33FD79FECB0419A5688035D7BCD3AEFE236"); - witnessMap.put(70,"41AF68F90ED62BA9F6F7A7EABA384E417551CF83E5"); - witnessMap.put(75,"41AF619F8CE75A9E95A19E851BEBE63E89FCB1826E"); - witnessMap.put(80,"41AF71E98F91515D7E5D5379837B9EEFD1AB4650D2"); - witnessMap.put(85,"41AF498B43EE098B26926798CFEAE1AB1154EF4430"); - witnessMap.put(90,"41AF536672333170CB0FBFA78819CD90A05537D872"); - witnessMap.put(95,"41AF5FAC2D62DD1F5C9892BA9D6593337ABBEAAACB"); - witnessMap.put(100,"41AF6981D4562E7B0A6C9E8F8C22D4CCCD03D2F39A"); - witnessMap.put(105,"41AF72A34243836238A533B7E77F3B2B29FD056B14"); - witnessMap.put(110,"41AF49C25D14AED36186B7C89AF405EF37A01EF23D"); - witnessMap.put(115,"41AF53BA37D394575CAD99A2A2C5BE56DEA0227C87"); - witnessMap.put(120,"41AF6A761C941AE2CDC75890D9900AC4B89B7EFCDD"); - witnessMap.put(125,"41AF72B56845F0C4D37388B6E6DC3601A0538ABA71"); - witnessMap.put(130,"41AF4ACF25C1E192285C9BA98522CB3CF20FFBE392"); - witnessMap.put(100000,"416C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - - - - for (String txid : listForTxid) { - - long blockNum = PublicMethed.getTransactionInfoById(txid,blockingStubFull) - .get().getBlockNumber(); - String witnessAddress = ByteArray.toHexString(PublicMethed - .getBlock(blockNum,blockingStubFull).getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()); - - map.put(witnessAddress.toLowerCase(), map.getOrDefault(witnessAddress,0) + 1); - logger.info("end"); - } - - } - - - - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void test02ScanBlockGetTransactionAndWriteToCsv() { - witnessMap.clear(); - map.clear(); - witnessMap.put(5,"41F08012B4881C320EB40B80F1228731898824E09D"); - witnessMap.put(10,"41DF309FEF25B311E7895562BD9E11AAB2A58816D2"); - witnessMap.put(15,"41BB7322198D273E39B940A5A4C955CB7199A0CDEE"); - witnessMap.put(20,"412080D8A0364E82150DD5235CE7A61A7B40F3F9EF"); - witnessMap.put(25,"4173FC381D3E2AFEFCCED94A57D49520291C38AFBB"); - witnessMap.put(30,"41AF6146B0AD9EE8BBEE811D5858F3252666DFC90C"); - witnessMap.put(35,"41AF6A9D9C0636BD9DF74F687B90C6F44C471A6AB3"); - witnessMap.put(40,"41AF730429E4AB7BF7B53FB15ACB1D45EF5B22F463"); - witnessMap.put(45,"41AF4AEA1C4CBCFA681D98C354C142938381C99389"); - witnessMap.put(50,"41AF53DC31D9DE64DFF59A847125EFCA89D97BC86D"); - witnessMap.put(55,"41AF49468FA1BA966244D76F7D0139FC2CA751FAA5"); - witnessMap.put(60,"41AF5360256F958D2A922D160C429F13D432EFC22F"); - witnessMap.put(65,"41AF5EF33FD79FECB0419A5688035D7BCD3AEFE236"); - witnessMap.put(70,"41AF68F90ED62BA9F6F7A7EABA384E417551CF83E5"); - witnessMap.put(75,"41AF619F8CE75A9E95A19E851BEBE63E89FCB1826E"); - witnessMap.put(80,"41AF71E98F91515D7E5D5379837B9EEFD1AB4650D2"); - witnessMap.put(85,"41AF498B43EE098B26926798CFEAE1AB1154EF4430"); - witnessMap.put(90,"41AF536672333170CB0FBFA78819CD90A05537D872"); - witnessMap.put(95,"41AF5FAC2D62DD1F5C9892BA9D6593337ABBEAAACB"); - witnessMap.put(100,"41AF6981D4562E7B0A6C9E8F8C22D4CCCD03D2F39A"); - witnessMap.put(105,"41AF72A34243836238A533B7E77F3B2B29FD056B14"); - witnessMap.put(110,"41AF49C25D14AED36186B7C89AF405EF37A01EF23D"); - witnessMap.put(115,"41AF53BA37D394575CAD99A2A2C5BE56DEA0227C87"); - witnessMap.put(120,"41AF6A761C941AE2CDC75890D9900AC4B89B7EFCDD"); - witnessMap.put(125,"41AF72B56845F0C4D37388B6E6DC3601A0538ABA71"); - witnessMap.put(130,"41AF4ACF25C1E192285C9BA98522CB3CF20FFBE392"); - witnessMap.put(100000,"416C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - - - Long startNum = 30855000L; - Long endNum = 30858000L; - - Integer totalNum = 0; - Integer successNum = 0; - Integer failedNum = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (endNum >= startNum) { - logger.info("scan block num:" + endNum); - builder.setNum(endNum); - Block block = blockingStubFull1.getBlockByNum(builder.build()); - List transactionList = block.getTransactionsList(); - map.put(ByteArray.toHexString(block.getBlockHeader().getRawData().getWitnessAddress() - .toByteArray()).toLowerCase(), - map.getOrDefault(ByteArray.toHexString(block.getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()).toLowerCase(),0) + 1); - Integer transactionNumInThisBlock = transactionList.size(); - totalNum = totalNum + transactionNumInThisBlock; - for (Transaction transaction : transactionList) { - String txid = ByteArray.toHexString(Sha256Hash.hash(true, - transaction.getRawData().toByteArray())); - //String writeData = ByteArray.toHexString(Sha256Hash.hash(true, - // transaction.getRawData().toByteArray())); - writeDataToCsvFile("txid-stressss.csv",txid); - //System.out.println("Fee:" + PublicMethed.getTransactionInfoById(txid, - // blockingStubFull).get().getFee()); - } - for (Transaction transaction : transactionList) { - if (transaction.getRet(0).getContractRet().name().equals("SUCCESS")) { - successNum++; - } else { - failedNum++; - - String writeData = ByteArray.toHexString(Sha256Hash.hash(true, - transaction.getRawData().toByteArray())); - logger.info(writeData); - writeDataToCsvFile("28164160L-28167324L.csv",writeData); - } - } - endNum--; - } - - logger.info("successNum:" + successNum); - logger.info("failedNum:" + failedNum); - logger.info("totalNum:" + totalNum); - logger.info("Success rate:" + (double)failedNum / (double)totalNum); - - - } - - public static Account account; - public HashSet addressSet = new HashSet<>(); - public HashSet assetIssueSet = new HashSet<>(); - - @Test(enabled = true, description = "Get account from transaction and compare " - + "account info from two different node") - public void test03CompareTwoNodeAccountStatus() throws Exception { - account = PublicMethed.queryAccount( - "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25",blockingStubFull); - //扫描到28307530块了 - Long startNum = 29266108L; - Long endNum = 29266208L; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum++ <= endNum) { - //Block block = blockingStubFull412.getNowBlock(EmptyMessage.newBuilder().build()); - builder.setNum(startNum); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("Start to scan block :" + block.getBlockHeader().getRawData().getNumber()); - - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - - Any any = transaction.getRawData().getContract(0).getParameter(); - Integer contractType = transaction.getRawData().getContract(0).getType().getNumber(); - - - try { - switch (contractType) { - case 1: - TransferContract transferContract = any.unpack(TransferContract.class); - set.add(transferContract.getOwnerAddress()); - break; - case 2: - TransferAssetContract transferAssetContract = any.unpack(TransferAssetContract.class); - doCheck(transferAssetContract.getOwnerAddress()); - if (!addressSet.contains(transferAssetContract.getAssetName())) { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray - .toStr(transferAssetContract.getAssetName().toByteArray()), - blockingStubFull), - PublicMethed.getAssetIssueById(ByteArray.toStr(transferAssetContract - .getAssetName().toByteArray()), blockingStubFull)); - addressSet.add(transferAssetContract.getAssetName()); - logger.info("check token " + ByteArray.toStr(transferAssetContract - .getAssetName().toByteArray()) + " successfully"); - } - break; - case 31: - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - doCheck(triggerSmartContract.getOwnerAddress()); - break; - case 13: - WithdrawBalanceContract withdrawBalanceContract - = any.unpack(WithdrawBalanceContract.class); - doCheck(withdrawBalanceContract.getOwnerAddress()); - break; - case 11: - FreezeBalanceContract freezeBalanceContract = any.unpack(FreezeBalanceContract.class); - doCheck(freezeBalanceContract.getOwnerAddress()); - break; - case 0: - AccountCreateContract accountCreateContract = any.unpack(AccountCreateContract.class); - doCheck(accountCreateContract.getOwnerAddress()); - break; - /* case 4: - VoteWitnessContract voteWitnessContract = any.unpack(VoteWitnessContract.class); - doCheck(voteWitnessContract.getOwnerAddress());*/ - case 12: - UnfreezeBalanceContract unfreezeBalanceContract - = any.unpack(UnfreezeBalanceContract.class); - doCheck(unfreezeBalanceContract.getOwnerAddress()); - break; - case 30: - CreateSmartContract createSmartContract = any.unpack(CreateSmartContract.class); - doCheck(createSmartContract.getOwnerAddress()); - break; - case 46: - AccountPermissionUpdateContract accountPermissionUpdateContract - = any.unpack(AccountPermissionUpdateContract.class); - doCheck(accountPermissionUpdateContract.getOwnerAddress()); - break; - default: - logger.info("Unknown type:" + contractType); - continue; - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - - - - - } - } - - - } - - - @Test(enabled = true, description = "Get all info from smart contract transaction list") - public void test04GetEventTransactionAllInfoList() throws Exception { - - - - HashSet contractAndTopicList = new HashSet<>(); - - - Long startNum = 33662515L - 9500; - Long endNum = startNum - 1000; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum-- >= endNum) { - logger.info("current block num:" + startNum); - builder.setNum(startNum); - TransactionInfoList transactionInfoList = blockingStubFull - .getTransactionInfoByBlockNum(builder.build()); - - for (TransactionInfo transactionInfo : transactionInfoList.getTransactionInfoList()) { - if (!transactionInfo.getContractAddress().isEmpty() && transactionInfo.getLogCount() > 0) { - try { - String txid = ByteArray.toHexString(transactionInfo.getId().toByteArray()); - Any any = PublicMethed.getTransactionById(txid, blockingStubFull).get().getRawData() - .getContract(0).getParameter(); - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(ByteArray.toHexString(triggerSmartContract - .getOwnerAddress().toByteArray())); - stringBuffer.append(","); - stringBuffer.append(ByteArray.toHexString(transactionInfo - .getContractAddress().toByteArray())); - stringBuffer.append(","); - stringBuffer.append(ByteArray.toHexString(triggerSmartContract - .getData().toByteArray())); - stringBuffer.append(","); - //stringBuffer.append(blockHash); - //stringBuffer.append(","); - //stringBuffer.append(startNum); - //stringBuffer.append(","); - stringBuffer.append(txid); - - - - - contractAndTopicList.add(stringBuffer.toString()); - - ; - } catch (Exception e) { - e.printStackTrace(); - - } - } - - - - - } - } - - for (String contractAddressAndTopic : contractAndTopicList) { - writeDataToCsvFile("eth_blockHash.csv", contractAddressAndTopic); - } - - - - } - - - @Test(enabled = true, description = "Get eth block query information") - public void test05CreateEthBlockHash() throws Exception { - HashSet contractAndTopicList = new HashSet<>(); - - - Long startNum = 33662515L; - Long endNum = startNum - 20000; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum-- >= endNum) { - logger.info("current block num:" + startNum); - builder.setNum(startNum); - String blockHash = ByteArray.toHexString(PublicMethed.getBlock(startNum + 1, - blockingStubFull).getBlockHeader().getRawData().getParentHash().toByteArray()); - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(blockHash); - stringBuffer.append(","); - stringBuffer.append(startNum); - contractAndTopicList.add(stringBuffer.toString()); - } - - for (String contractAddressAndTopic : contractAndTopicList) { - writeDataToCsvFile("eth_blockHash.csv", contractAddressAndTopic); - } - - - - } - - - ConcurrentHashMap certificationCosts = new ConcurrentHashMap<>(); - Set concurrentHashSet = certificationCosts.newKeySet(); - private static HashSet existAddress = new HashSet<>(); - List list1 = new ArrayList<>(); - - private static AtomicLong blockNum = new AtomicLong(30000523L - 20000L); - private static AtomicLong times = new AtomicLong(5); - - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void test06ScanMainNetMostActiveAccounts() throws Exception { - getNowAddressList(); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - long blockNumCurrent = blockNum.getAndAdd(-200); - int times = 200; - while (times-- >= 0) { - if (concurrentHashSet.size() > 1000000) { - break; - } - //list1.add(blockNumCurrent); - builder.setNum(blockNumCurrent--); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("Start to scan block :" + block.getBlockHeader().getRawData().getNumber()); - - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - - Any any = transaction.getRawData().getContract(0).getParameter(); - Integer contractType = transaction.getRawData().getContract(0).getType().getNumber(); - - - try { - switch (contractType) { - case 1: - TransferContract transferContract = any.unpack(TransferContract.class); - isExist(transferContract.getOwnerAddress()); - isExist(transferContract.getToAddress()); - break; - case 2: - TransferAssetContract transferAssetContract = any.unpack(TransferAssetContract.class); - isExist(transferAssetContract.getOwnerAddress()); - isExist(transferAssetContract.getToAddress()); - break; - case 31: - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - isExist(triggerSmartContract.getContractAddress()); - isExist(triggerSmartContract.getOwnerAddress()); - break; - case 13: - WithdrawBalanceContract withdrawBalanceContract - = any.unpack(WithdrawBalanceContract.class); - - isExist(withdrawBalanceContract.getOwnerAddress()); - break; - case 11: - FreezeBalanceContract freezeBalanceContract = any.unpack(FreezeBalanceContract.class); - isExist(freezeBalanceContract.getOwnerAddress()); - break; - case 0: - AccountCreateContract accountCreateContract = any.unpack(AccountCreateContract.class); - isExist(accountCreateContract.getOwnerAddress()); - isExist(accountCreateContract.getAccountAddress()); - break; - case 12: - UnfreezeBalanceContract unfreezeBalanceContract - = any.unpack(UnfreezeBalanceContract.class); - isExist(unfreezeBalanceContract.getOwnerAddress()); - break; - case 30: - CreateSmartContract createSmartContract = any.unpack(CreateSmartContract.class); - isExist(createSmartContract.getOwnerAddress()); - break; - case 46: - AccountPermissionUpdateContract accountPermissionUpdateContract - = any.unpack(AccountPermissionUpdateContract.class); - isExist(accountPermissionUpdateContract.getOwnerAddress()); - break; - case 4: - VoteWitnessContract voteWitnessContract = any.unpack(VoteWitnessContract.class); - isExist(voteWitnessContract.getOwnerAddress()); - break; - default: - logger.info("Unknown type:" + contractType); - continue; - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - - - - - - } - } - - - - - } - - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test07ScanAndCalculateTotalValueOrCallValue() throws Exception { - getNowAddressList(); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget("47.252.19.181:50051") - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - int total1 = 0; - int total2 = 0; - int totalTrx = 0; - for (long blockNum = 20450668L; blockNum <= 20450790L;blockNum++) { - System.out.println("blockNum " + blockNum); - TransactionInfoList transactionList = PublicMethed.getTransactionInfoByBlockNum(blockNum, - blockingStubFull).get(); - for (int i = 0; i < transactionList.getTransactionInfoCount();i++) { - if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getContractAddress() - .toByteArray()).equalsIgnoreCase("41DF42D1936F0DC3689BB65A19F279747084E13FBD")) { - - - if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "9b217a401a5ddf7c4d474074aff9958a18d48690d77cc2151c4706aa7348b401")) { - total1 += Integer.parseInt(ByteArray.toHexString(transactionList.getTransactionInfo(i) - .getLog(0).getData().toByteArray()),16); - } else if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "31472eae9e158460fea5622d1fcb0c5bdc65b6ffb51827f7bc9ef5788410c34c")) { - total2 += Integer.parseInt(ByteArray.toHexString(transactionList.getTransactionInfo(i) - .getLog(0).getData().toByteArray()),16); - } else if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "3e799b2d61372379e767ef8f04d65089179b7a6f63f9be3065806456c7309f1b")) { - totalTrx += transactionList.getTransactionInfo(i).getInternalTransactions(4) - .getCallValueInfo(0).getCallValue(); - } - - } - } - } - - System.out.println("total1 :" + total1); - System.out.println("total2 :" + total2); - System.out.println("total_callValue :" + totalTrx); - - } - - - - @Test - public void test08ScanAndCalculateWitnessProductBlockStatus() { - Long startNum = 33694340L; - Long endNum = 33694388L; - - Integer testgroup014 = 0; - Integer testgroup015 = 0; - Integer testgroup016 = 0; - Integer testgroup017 = 0; - Integer testgroup018 = 0; - - int transfer = 0; - int trigger = 0; - - while (startNum++ <= endNum) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("current block:" + startNum); - - String currentAddress = ByteArray.toHexString(block.getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()); - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - if (transaction.getRawData().getContract(0).getType().equals(ContractType - .TriggerSmartContract)) { - trigger++; - } else { - transfer++; - } - } - if (currentAddress.equals(getHexAddress( - "0528dc17428585fc4dece68b79fa7912270a1fe8e85f244372f59eb7e8925e04")) - || currentAddress - .equals(getHexAddress( - "dbc78781ad27f3751358333412d5edc85b13e5eee129a1a77f7232baadafae0e")) - || currentAddress - .equals(getHexAddress( - "a79a37a3d868e66456d76b233cb894d664b75fd91861340f3843db05ab3a8c66")) - || currentAddress - .equals(getHexAddress( - "a8107ea1c97c90cd4d84e79cd79d327def6362cc6fd498fc3d3766a6a71924f6")) - || currentAddress - .equals(getHexAddress( - "b5076206430b2ca069ae2f4dc6f20dd0d74551559878990d1df12a723c228039")) - || currentAddress - .equals(getHexAddress( - "87cc8832b1b4860c3c69994bbfcdae9b520e6ce40cbe2a90566e707a7e04fc70")) - ) { - testgroup014++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "553c7b0dee17d3f5b334925f5a90fe99fb0b93d47073d69ec33eead8459d171e")) - || currentAddress - .equals(getHexAddress( - "541a2d585fcea7e9b1803df4eb49af0eb09f1fa2ce06aa5b8ed60ac95655d66d")) - || currentAddress - .equals(getHexAddress( - "7d5a7396d6430edb7f66aa5736ef388f2bea862c9259de8ad8c2cfe080f6f5a0")) - || currentAddress - .equals(getHexAddress( - "7c4977817417495f4ca0c35ab3d5a25e247355d68f89f593f3fea2ab62c8644f")) - || currentAddress - .equals(getHexAddress( - "4521c13f65cc9f5c1daa56923b8598d4015801ad28379675c64106f5f6afec30")) - || currentAddress - .equals(getHexAddress( - "442513e2e801bc42d14d33b8148851dae756d08eeb48881a44e1b2002b3fb700")) - ) { - testgroup015++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096c6bacb8")) - || currentAddress - .equals(getHexAddress( - "f33101ea976d90491dcb9669be568db8bbc1ad23d90be4dede094976b67d550e")) - || currentAddress - .equals(getHexAddress( - "1bb32958909299db452d3c9bbfd15fd745160d63e4985357874ee57708435a00")) - || currentAddress - .equals(getHexAddress( - "29c91bd8b27c807d8dc2d2991aa0fbeafe7f54f4de9fac1e1684aa57242e3922")) - || currentAddress - .equals(getHexAddress( - "97317d4d68a0c5ce14e74ad04dfc7521f142f5c0f247b632c8f94c755bdbe669")) - ) { - testgroup016++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "ff5d867c4434ac17d264afc6696e15365832d5e8000f75733ebb336d66df148d")) - || currentAddress - .equals(getHexAddress( - "1fe1d91bbe3ac4ac5dc9866c157ef7615ec248e3fd4f7d2b49b0428da5e046b2")) - || currentAddress - .equals(getHexAddress( - "7c37ef485e186e07952bcc8e30cd911a6cd9f2a847736c89132762fb67a42329")) - || currentAddress - .equals(getHexAddress( - "bcc142d57d872cd2cc1235bca454f2efd5a87f612856c979cc5b45a7399272a8")) - || currentAddress - .equals(getHexAddress( - "6054824dc03546f903a06da1f405e72409379b83395d0bbb3d4563f56e828d52")) - ) { - testgroup017++; - continue; - } - - testgroup018++; - } - - - logger.info(testgroup014 + " " + testgroup015 + " " - + testgroup016 + " " + testgroup017 + " " + testgroup018); - - logger.info(transfer + " " + trigger); - - - } - - - @Test - public void test09GetEthFilterData() { - - HashSet set = new HashSet<>(); - Integer startBlockNumber = 35129811 - 2000; - Integer endBlockNumber = startBlockNumber - 3000; - - for (int blockNumber = startBlockNumber; blockNumber >= endBlockNumber;blockNumber-- - ) { - set.clear(); - HttpResponse response = HttpMethed - .getTransactionInfoByBlocknum("1.1.1.1:90", blockNumber); - - List content = HttpMethed.parseResponseContentArray(response); - - String blockNumberHex = "0x" + Integer.toHexString(blockNumber); - - System.out.println(content.size()); - for (JSONObject info : content) { - if (!info.containsKey("log")) { - continue; - } - JSONArray logArray = info.getJSONArray("log"); - for (int i = 0; i < logArray.size();i++) { - JSONObject log = logArray.getJSONObject(i); - String address = "0x" + log.getString("address"); - String topic = "0x" + log.getJSONArray("topics").getString(0); - set.add(address + "," + topic + "," + blockNumberHex); - - } - - - - - } - - for (String data : set) { - writeDataToCsvFile("ys_filter_api.csv", data); - } - } - - - } - - public String getHexAddress(String key) { - return ByteArray.toHexString(PublicMethed.getFinalAddress(key)); - } - - private static HashSet getFileList(String fileName,HashSet set) { - String line = null; - try { - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"utf-8")); - - while ((line = bufferedReader.readLine()) != null) { - set.add(line); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return set; - } - - - - - private static void getNowAddressList() { - String line = null; - try { - //BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath)); - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(new FileInputStream("newAddress.csv"),"utf-8")); - - //int i=0; - while ((line = bufferedReader.readLine()) != null) { - existAddress.add(line); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - - /** - * constructor. - */ - public static void writeDataToCsvFile(String fileName,String writeData) { - - { - try { - File file = new File(fileName); - - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fileWritter = new FileWriter(file.getName(), true); - fileWritter.write(writeData + "\n"); - fileWritter.close(); - //System.out.println("finish"); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - /** - * constructor. - */ - public void doCheck(ByteString address) throws Exception { - if (addressSet.contains(address)) { - //logger.info("skip :" + ByteArray.toHexString(address.toByteArray())); - return; - } else { - addressSet.add(address); - } - logger.info("checking :" + ByteArray.toHexString(address.toByteArray())); - compareTwoAddress(address); - compareNet(address); - compareAccountResource(address); - return; - - } - - /** - * constructor. - */ - public void compareTwoAddress(ByteString address) { - - Assert.assertEquals( - PublicMethed.queryAccount(address.toByteArray(),blockingStubFull).toBuilder() - .clearFreeAssetNetUsageV2() - //.putAllFreeAssetNetUsageV2(account.getFreeAssetNetUsageV2Map()) - .setBalance(1L).setLatestOprationTime(1L) - .setAccountResource(AccountResource.newBuilder()) - .setFreeNetUsage(1L) - .setNetUsage(1L) - .clearAssetV2() - .setLatestConsumeFreeTime(1L) - .setLatestConsumeTime(1L) - .setAllowance(1L) - .clearAccountResource() - //.clearOldVotePower() - .build(), - PublicMethed.queryAccount(address.toByteArray(),blockingStubFull).toBuilder() - .clearFreeAssetNetUsageV2() - //.putAllFreeAssetNetUsageV2(account.getFreeAssetNetUsageV2Map()) - .setBalance(1L).setLatestOprationTime(1L) - .setAccountResource(AccountResource.newBuilder()) - .setFreeNetUsage(1L) - .setNetUsage(1L) - .setLatestConsumeFreeTime(1L) - .setLatestConsumeTime(1L) - .clearAssetV2() - .setAllowance(1L) - .clearAccountResource() - .build() - ); - - } - - - /** - * constructor. - */ - public void compareNet(ByteString address) { - Assert.assertEquals( - PublicMethed.getAccountNet(address.toByteArray(),blockingStubFull) - .toBuilder().setTotalNetWeight(1L) - .setNetUsed(1L) - .setFreeNetUsed(1) - .setNetLimit(1) - .build(), - PublicMethed.getAccountNet(address.toByteArray(),blockingStubFull) - .toBuilder().setTotalNetWeight(1L) - .setNetUsed(1L) - .setFreeNetUsed(1) - .setNetLimit(1) - .build() - ); - } - - /** - * constructor. - */ - public void compareAccountResource(ByteString address) throws Exception { - Assert.assertEquals( - PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build(), - PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setEnergyLimit(1L) - .build() - ); - - } - - /** - * constructor. - */ - public boolean isEqual(ByteString address) { - return PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build().equals(PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build()); - - } - - /** - * constructor. - */ - public void isExist(ByteString address1) { - byte[] address = address1.toByteArray(); - byte[] hash0 = Sha256Sm3Hash.hash(address); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); - byte[] checkSum = Arrays.copyOfRange(hash1, 0, 4); - byte[] addchecksum = new byte[address.length + 4]; - System.arraycopy(address, 0, addchecksum, 0, address.length); - System.arraycopy(checkSum, 0, addchecksum, address.length, 4); - if (!existAddress.contains(Base58.encode(addchecksum))) { - concurrentHashSet.add(address1); - } - } - - /** - * constructor. - */ - private static void getTxidList() { - String line = null; - try { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new - FileInputStream("demo.csv"),"utf-8")); - - while ((line = bufferedReader.readLine()) != null) { - listForTxid.add(line.toLowerCase()); - - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - List list = new ArrayList<>(concurrentHashSet); - for (ByteString target : list) { - byte[] address = target.toByteArray(); - byte[] hash0 = Sha256Sm3Hash.hash(address); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); - byte[] checkSum = Arrays.copyOfRange(hash1, 0, 4); - byte[] addchecksum = new byte[address.length + 4]; - System.arraycopy(address, 0, addchecksum, 0, address.length); - System.arraycopy(checkSum, 0, addchecksum, address.length, 4); - writeDataToCsvFile("newAddress.csv", Base58.encode(addchecksum)); - } - Collections.sort(list1); - - - int i = 1; - /* - afterTime = System.currentTimeMillis(); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock.getBlockHeader().getRawData().getNumber() + 2; - Long blockNum = beforeBlockNum; - Integer txsNum = 0; - Integer topNum = 0; - Integer totalNum = 0; - Long energyTotal = 0L; - String findOneTxid = ""; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (blockNum <= afterBlockNum) { - builder.setNum(blockNum); - txsNum = blockingStubFull1.getBlockByNum(builder.build()).getTransactionsCount(); - totalNum = totalNum + txsNum; - if (topNum < txsNum) { - topNum = txsNum; - findOneTxid = ByteArray.toHexString(Sha256Hash.hash(blockingStubFull1 - .getBlockByNum(builder.build()).getTransactionsList().get(2) - .getRawData().toByteArray())); - //logger.info("find one txid is " + findOneTxid); - } - - blockNum++; - } - Long costTime = (afterTime - beforeTime - 31000) / 1000; - logger.info("Duration block num is " + (afterBlockNum - beforeBlockNum - 11)); - logger.info("Cost time are " + costTime); - logger.info("Top block txs num is " + topNum); - logger.info("Total transaction is " + (totalNum - 30)); - logger.info("Average Tps is " + (totalNum / costTime)); - - infoById = PublicMethed.getTransactionInfoById(findOneTxid, blockingStubFull1); - Long oneEnergyTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("EnergyTotal is " + oneEnergyTotal); - logger.info("Average energy is " + oneEnergyTotal * (totalNum / costTime)); - */ - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java deleted file mode 100644 index 92118d87fcc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class ShieldTrc10Stress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Optional sendShieldAddressInfo; - String sendshieldAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20000 * zenTokenFee; - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - - String memo = "Use to TestZenToken004 shield address"; - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, threadPoolSize = 100, invocationCount = 100) - public void test1Shield2TwoShieldTransaction() { - ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - DecryptNotes notes; - List shieldOutList = new ArrayList<>(); - - Integer times = 100; - while (times-- > 0) { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //logger.info("note size:" + notes.getNoteTxsCount()); - - String memo1 = "Shield to shield address1 transaction" + System.currentTimeMillis(); - shieldOutList.clear(); - Long sendToShiledAddress1Amount = - notes.getNoteTxs(notes.getNoteTxsCount() - 1).getNote().getValue() - zenTokenFee; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + sendToShiledAddress1Amount, memo1); - - try { - PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(notes.getNoteTxsCount() - 1), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - } catch (Exception e) { - throw e; - } - } - - } - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java deleted file mode 100644 index e50f30b869a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java +++ /dev/null @@ -1,719 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Stress extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional sendShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - - - private AtomicInteger finishMintNumber = new AtomicInteger(0); - private AtomicInteger finishCreateParameterNumber = new AtomicInteger(0); - private AtomicInteger finishTriggerNumber = new AtomicInteger(0); - private AtomicInteger noteNumber = new AtomicInteger(0); - private AtomicInteger dataNumber = new AtomicInteger(0); - private AtomicLong startTriggerNum = new AtomicLong(0); - private AtomicLong endTriggerNum = new AtomicLong(0); - private AtomicLong startmintNum = new AtomicLong(0); - private AtomicLong endmintNum = new AtomicLong(0); - private Integer thread = 40; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - publicFromAmount = getRandomAmount(); - //startQureyNum = HttpMethed.getNowBlockNum(httpnode); - startmintNum.addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - } - - /** - * wqs constructor. - */ - @Test(enabled = false, threadPoolSize = 50, invocationCount = 50) - public void test01ScanAndCreateThenTrigger() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - BigInteger publicFromAmount = getRandomAmount(); - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 sendNote; - List inputList = new ArrayList<>(); - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - while (sendNote.getNoteTxsCount() == 0) { - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - } - - Integer times = 20; - while (times-- > 0) { - //receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - //Scan sender note - /*sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - while (sendNote.getNoteTxsCount() == 0) { - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - }*/ - - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - String transferMemo = "Transfer type test " + System.currentTimeMillis(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, transferMemo, blockingStubFull); - - //logger.info("send note size:" + sendNote.getNoteTxsCount()); - - //Create transfer parameters - try { - GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(sendNote.getNoteTxsCount() - 1)).build(); - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull1, blockingStubSolidity); - } catch (Exception e) { - throw e; - } - - Integer exit = 7; - if (exit == 1) { - continue; - } - - data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - - //sendShieldAddressInfo = receiverShieldAddressInfo; - } - - } - - - /** - * constructor. - */ - @Test(enabled = false, threadPoolSize = 40, invocationCount = 40) - public void test02FirstScanCreateParameterThenCreateTrigger() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - - Integer mintNumber = 50; - - while (--mintNumber >= 0) { - BigInteger publicFromAmount = getRandomAmount(); - - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity - ); - String data = ""; - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e) { - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e1) { - continue; - } - - } - - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - finishMintNumber.addAndGet(1); - endmintNum.getAndAdd(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - while (finishMintNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishMintNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished mint,current finished thread is :" + finishMintNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Long endMintNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - GrpcAPI.DecryptNotesTRC20 sendNote = scanShieldedTrc20NoteByIvkWithRange( - sendShieldAddressInfo.get(), - startmintNum.get(), endMintNum, blockingStubFull1); - - noteNumber.addAndGet(sendNote.getNoteTxsCount()); - - logger.info("sendNote size :" + sendNote.getNoteTxsCount()); - - List shieldOutList = new ArrayList<>(); - - List inputShieldAddressList = new ArrayList<>(); - - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - List dataList = new ArrayList<>(); - for (int i = 0; i < sendNote.getNoteTxsCount() - 1; i = i + 2) { - GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(i)) - .addNoteTxs(sendNote.getNoteTxs(i + 1)) - .build(); - - String transferMemo1 = "Transfer1 type test " + getRandomLongAmount() + getRandomLongAmount(); - String transferMemo2 = "Transfer2 type test " + getRandomLongAmount() + getRandomLongAmount(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, - receiverShieldAddressInfo.get().getAddress(), - "" + sendNote.getNoteTxs(i).getNote().getValue(), transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, - receiverShieldAddressInfo.get().getAddress(), - "" + sendNote.getNoteTxs(i + 1).getNote().getValue(), transferMemo2, blockingStubFull); - - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters = null; - if (i % 2 == 0) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull1, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - } - - } else { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull1, blockingStubSolidity); - } catch (Exception e2) { - throw e2; - } - - - } - } - - dataList.add(encodeTransferParamsToHexString(shieldedTrc20Parameters)); - //logger.info("dataList size:" + dataList.size()); - - } - - finishCreateParameterNumber.addAndGet(1); - dataNumber.addAndGet(dataList.size()); - while (finishCreateParameterNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishCreateParameterNumber.get() % 10 == 0) { - logger.info("Wait all thread finished create parameter ,current finished thread is :" - + finishCreateParameterNumber.get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - startTriggerNum - .addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - for (int i = 0; i < dataList.size(); i++) { - if (i % 2 == 0) { - PublicMethed.triggerContract(shieldAddressByte, - transfer, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - } else { - PublicMethed.triggerContract(shieldAddressByte, - transfer, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull1); - } - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - finishTriggerNumber.addAndGet(1); - - while (finishTriggerNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishTriggerNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished trigger ,current finished thread is :" + finishTriggerNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - - } - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 40, invocationCount = 40) - public void test03BurnStress() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - - Integer mintNumber = 25; - - while (--mintNumber >= 0) { - BigInteger publicFromAmount = getRandomAmount(); - - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity - ); - String data = ""; - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e) { - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e1) { - continue; - } - - } - - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - finishMintNumber.addAndGet(1); - endmintNum.getAndAdd(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - while (finishMintNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishMintNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished mint,current finished thread is :" + finishMintNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - Long endMintNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - GrpcAPI.DecryptNotesTRC20 sendNote = scanShieldedTrc20NoteByIvkWithRange( - sendShieldAddressInfo.get(), - startmintNum.get(), endMintNum, blockingStubFull1); - - noteNumber.addAndGet(sendNote.getNoteTxsCount()); - - logger.info("sendNote size :" + sendNote.getNoteTxsCount()); - - List shieldOutList = new ArrayList<>(); - - List inputShieldAddressList = new ArrayList<>(); - - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - List dataList = new ArrayList<>(); - for (int i = 0; i < sendNote.getNoteTxsCount(); i++) { - String burnnMemo1 = "burnnMemo1 type test " + getRandomLongAmount() + getRandomLongAmount(); - GrpcAPI.DecryptNotesTRC20 burnInput = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(i)) - .build(); - - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters = null; - createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - - if (i % 2 == 0) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull1, - blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - } - - } else { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull1, - blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - - } - } - - dataList.add(shieldedTrc20Parameters.getTriggerContractInput()); - - } - - finishCreateParameterNumber.addAndGet(1); - dataNumber.addAndGet(dataList.size()); - while (finishCreateParameterNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishCreateParameterNumber.get() % 10 == 0) { - logger.info("Wait all thread finished create parameter ,current finished thread is :" - + finishCreateParameterNumber.get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - startTriggerNum - .addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - for (int i = 0; i < dataList.size(); i++) { - if (i % 2 == 0) { - PublicMethed.triggerContract(shieldAddressByte, - burn, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - } else { - PublicMethed.triggerContract(shieldAddressByte, - burn, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull1); - } - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - finishTriggerNumber.addAndGet(1); - - while (finishTriggerNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishTriggerNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished trigger ,current finished thread is :" + finishTriggerNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - - } - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test04QueryResult() throws Exception { - - endTriggerNum.set(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - Long endmintnum = endmintNum.longValue() / thread; - Long starttriggernum = startTriggerNum.longValue() / thread; - logger.info("Start trigger block number: " + starttriggernum); - logger.info("end trigger block number: " + endTriggerNum.get()); - logger.info("Start mint block number: " + startmintNum.get()); - logger.info("End mint block number: " + endmintnum); - - Integer success = 0; - Integer failed = 0; - Integer outOfTime = 0; - Integer notMintContract = 0; - startmintNum.getAndAdd(-5); - endmintnum = endmintnum + 5; - - startmintNum.set(2016); - endmintnum = 2180L; - starttriggernum = 3040L; - endTriggerNum.set(3060); - - while (startmintNum.get() < endmintnum) { - HttpResponse response = HttpMethed - .getTransactionInfoByBlocknum(httpnode, startmintNum.getAndAdd(1)); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(response); - for (int i = 0; i < responseContentByBlocknum.size(); i++) { - String result = responseContentByBlocknum.get(i).getJSONObject("receipt") - .getString("result"); - logger.info(result); - if (result == null) { - notMintContract++; - continue; - } - if (result.equals("SUCCESS")) { - success++; - continue; - } - if (result.equals("OUT_OF_TIME")) { - outOfTime++; - continue; - } - failed++; - } - } - - Integer triggerSuccess = 0; - Integer triggerFailed = 0; - Integer triggerOutOfTime = 0; - Integer notTriggerContract = 0; - startTriggerNum.getAndAdd(-5); - endTriggerNum.getAndAdd(5); - - while (starttriggernum < endTriggerNum.get()) { - HttpResponse response = HttpMethed.getTransactionInfoByBlocknum(httpnode, starttriggernum++); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(response); - for (int i = 0; i < responseContentByBlocknum.size(); i++) { - String result = responseContentByBlocknum.get(i).getJSONObject("receipt") - .getString("result"); - logger.info(result); - if (result == null) { - notTriggerContract++; - continue; - } - if (result.equals("SUCCESS")) { - triggerSuccess++; - continue; - } - if (result.equals("OUT_OF_TIME")) { - triggerOutOfTime++; - continue; - } - triggerFailed++; - } - } - - logger.info("Mint Success mint times:" + success); - logger.info("Mint Failed mint times:" + failed); - logger.info("Mint Out of times mint times:" + outOfTime); - logger.info("Not mint times:" + notMintContract); - - logger.info("Success trigger times:" + triggerSuccess); - logger.info("Failed trigger times:" + triggerFailed); - logger.info("Out of times trigger times:" + triggerOutOfTime); - logger.info("Not trigger times:" + notTriggerContract); - - logger.info("note size:" + noteNumber.get()); - logger.info("data size:" + dataNumber.get()); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - //endNum = HttpMethed.getNowBlockNum(httpnode); - //logger.info("startNum:" + startNum); - //logger.info("endNum:" + endNum); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java deleted file mode 100644 index 4b7ede49ab8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java +++ /dev/null @@ -1,374 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class SupportTronlinkAutoTest { - - private final String testKey002 - = "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - //Mainnet fullnode - private String fullnode = "47.252.19.181:50051"; - //dappchain fullnode - //private String fullnode = "47.252.7.241:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForAccount() { - Integer i = 0; - System.out.println("Start genterate address"); - while (i++ < 20) { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - //PublicMethed.printAddress(ownerKey); - - PublicMethed.sendcoin(ownerAddress, 200000000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = ownerKey; - ownerKeyString[0] = ownerKey; - //ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"" - + "7fff1fc0033e0b00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - System.out.println("owner" + i + " --------------------------------------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("mutli sig address for owner " - + i + " ----------------------------------"); - PublicMethed.printAddress(manager1Key); - System.out.println("-------------------------------" - + "-----------------------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test002CreateWitness() { - Integer i = 0; - System.out.println("Start genterate witness address"); - while (i++ < 10) { - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - //PublicMethed.printAddress(ownerKey); - - PublicMethed.sendcoin(ownerAddress, 50000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String createWitnessUrl = "IOS-UI-Witness-00" + i; - byte[] createUrl = createWitnessUrl.getBytes(); - createWitness(ownerAddress, createUrl, ownerKey); - PublicMethed.waitProduceNextBlock(blockingStubFull); - System.out.println("witness " + i + " -----------------------------" - + "---------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("witness url is : " + createWitnessUrl); - System.out.println("-------------------------------------------" - + "-----------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test03MutiSignForAccount() { - HashMap muti = new HashMap(); - muti.put("9a2ba173645be8d37a82084f984ba873fbcf817b589c62a59b3ba1494c3406e0", - "cefba96470224724bde255f3402fca3d67b6c7c5d34deb7a8524c9482c58fe8b"); - muti.put("36f5430b4003f41ee8969421d9366ab1414e62111aec07a73d06eefcda8aad14", - "3adcd73ad1fa03ce2fd4d29e29a7c96ef2f78bece85cba6e58997826682c4c1e"); - muti.put("4b47cf37528724dc8bc99188063f5aec9a7bc32aadfad5a96a9e9cccba7cede1", - "948d856ebeb787aabd495fc13627f7442e7c1f21e9ed784f795e14f13cbebb94"); - muti.put("75d0856799cf2b2c807ed0eb5bb091bb943f2caed830add4b8df14c537f86e9a", - "7fb13ad0b62d4ff116ebd3d901d458697902ce81a8fc30c20c60aba1ca6964ec"); - muti.put("327bf1b4a3193c2bebf239c1c5bda09a8d375251361ea9c7418aa2adf2d17b7e", - "a8236968966db785ffe63d613174ee25e1baff03817b64db905c5940ed3dcc4b"); - muti.put("cf83d9494a9268fd3a75bd76bcfabaa7ec766e9084129a20e1823f81fbdca933", - "1e53c948e949e39f60a3be2382382f9a50f88b658ea79c418ece1c5f9b169441"); - muti.put("19ff919e92462f07c7eced256d4cb588a66ac900d544d0d4d16ae49732de79cb", - "166ddc2cd6379e7971e2c65d224594b709ebb59b3c6051c156214c299129f420"); - muti.put("7901db57a410a26d333b6d7fe4e054ddffbdc646f94ca03577bfd5e87120b9af", - "89d9a47b37f5625e14082b575d5e657b21f6dae125125bee51fafd1e8cdf0804"); - muti.put("e3c7204d652a6fdcda05cbce061904d441dece7bf0a1778c1ddf0906aa36a279", - "7d308998f829c0581447831003d994216a3a003ba00eef6a4e48e28b3178fbb3"); - muti.put("826fc86d572ba9de06f20963fcbfb44f4c397875bd4d7b36fdcb83476df33f05", - "25aa122142a52ea8ba7bdf832c39a194d498774d4f675b8bcb17280c33990a08"); - muti.put("9705dd852465d04be349e94865142fc636d038138a4bfe8f94abc9b49f1dc14a", - "0b675f14c1e06a6473c517dded162472ce2bb5c8934f198df1a791b75c30f983"); - muti.put("075f86d3d4053929714ddedb3e458467e6d494c3d4b0c71dafb63279de1beb89", - "4880695a6e31f4f69d6f261eedfa5dcb5fc1b9194483658f77625ec4e6b2e493"); - muti.put("91ae6c8a1bff0b71f6f2b9de54d3b39502bcab906f980569109ab8425cb0bdc5", - "90ef4adb0772ee49089784ccad234867a10395064749788b461cbe91265424fb"); - muti.put("9acb90c4d15c87dd2a1f322eddaabdde22cd78fe5eab371bfcf0c8be80bef8a8", - "951f03193e1d7d4bff016da100b74f8ac220aabfd9c2841438ee758702c8e3f4"); - muti.put("f8eae7be0fac4e9fab40139e58b405f7e5d5b13a83220a6e4955ffaacbbe2a7d", - "66692c0aaad6cfd349bdffbf3fdd688558a6c7a95ff67f249e0e80847167013a"); - muti.put("2e20c1a4b9a3a79696cbf0d03dedc39d8021657028fbf3dbc5da85ea61ad5dff", - "ae7ecb7fba0d77d116a23f96a4dfecdef09741e363f0be12f99c86b3815d8fff"); - muti.put("e5e60c52f3b11ce0cfbc4e86d078ab53435ebc2422fd851614a25b5063ae7040", - "42c575d8848809082c6872b2dcdb0e81d5f06ca120c636b90d0b062965ea0871"); - muti.put("fd4ee3a678a749c2049d5b1cba757648386c84ac2481be8de02069d41e4fb312", - "ef2095532f572be8d021886780f7e508665ef40c1499273b91813ddc27d1354b"); - muti.put("297f6e034e9366691922ff5394810f724094bd0a07b4ca60f0f281ec71562094", - "4ab67f1c42db0b63bafc0f33cf59575998c3259e96f5f89ea379dac4298d2bd7"); - int i = 1; - for (HashMap.Entry entry : muti.entrySet()) { - //entry.getKey().toString(); - //entry.getValue().toString(); - - ownerKey = entry.getKey().toString(); - ownerAddress = PublicMethed.getFinalAddress(ownerKey); - - manager1Key = entry.getValue().toString(); - manager1Address = PublicMethed.getFinalAddress(manager1Key); - - //System.out.println("ownerKey:" + ownerKey); - //System.out.println("manager1Key:" + manager1Key); - - //System.exit(1); - PublicMethed.sendcoin(ownerAddress, 20000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = ownerKey; - ownerKeyString[0] = ownerKey; - //ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"" - + "threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active\",\"threshold\":2," - + "\"operations\":\"" - + "7fff1fc0033e0b00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - System.out.println("owner " + i++ + " -----------------" - + "---------------------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("mutli sig address for owner " + i++ + " ------------" - + "----------------------"); - PublicMethed.printAddress(manager1Key); - System.out.println("-----------------------------------" - + "-------------------------------------"); - - } - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test004CreateWitness() { - - String[] witnessKey = { - - "c74fb4d8101572041c6fab30e1602ba1ec8247e1ead19641fb985b3ed3a8261e", - "25f98ac22c9fd02aa8a2ef354db0aa13ebc2a6c31377ea7e2b342f0d3898af0d", - "939a2cec3768bd2d2834126c20d2b1c513e3711f085ce374f654a7b144aa409f", - "39862f4dd51972ca22ce50b7b9e629043387000120c33bf263399ad9b334da1a", - "79045aab0f3199ac456ce2039e809e6c942983ede0e3a398d571dedddb351348", - "d50fe9c48e95289cde324ffeff095f8275f9ab07375e5e843167a0a54d3e1462", - "61651f2b8a87e1ae0ced5e700807f2abb50e97fe7d3d3e6a8aa58f0a6b0149a6", - "bb03d70e5187258ffb6cddb1becade5c1b2606b7ea84636b7dfaeef6216610a5", - "25858c236634e353d018f310f61e077b78e1410766565ed56ff11ee7410dcf20", - "ede941a01eb8234866f60c7e8e95db4614bb0d05298d82bae0abea81f1861046", - - }; - int i = 1; - for (String ownerKey : witnessKey) { - byte[] ownerAddress = PublicMethed.getFinalAddress(ownerKey); - PublicMethed.sendcoin(ownerAddress, 20000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String createWitnessUrl = "IOS-UI-Witness-00" + i++; - byte[] createUrl = createWitnessUrl.getBytes(); - createWitness(ownerAddress, createUrl, ownerKey); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(ownerKey); - System.out.println("witness url is : " + createWitnessUrl); - System.out.println("---------------------------------------------------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test005SendTrc20() { - - String[] witnessKey = { - "TR8CyAPJFMjCvphCVuWeeVxBh5iTG7VWxe", - "TMhGDU7NiXwckCW64PqAvWFuC2kR1WSF5J", - "TDf3JZtjDeEqsFdPGp6vT9meG3JxMwmXwA", - "TEtG9fnVi2qythiog6owPrg4sD9rwFBQBN", - "TUvda1oqrNLbqDKhZDxDnrPhiDCdxem218", - "TKEH31jJ2YQ3Bteh1ngjwdT8667ztyYPSp", - "TAzrJHKa57nXnn3dZGFG87PDuWx12dY97s", - "TWhc6AAh6BWRr3k5dV8iMvkp8ys7NHzXCk", - "TSsaSxHnb3xLTop2A8LrDk1P896yiDeupe", - "TMDs8oTj8mVnakqiVyDKdp2ruWPdFeDgbq", - "TWv2FEsoPp5XKxujVHffoNwksgJSxvf3QG", - "TGamEmt6U9ZUg9bFsMq7KT9bRa3uvkdtHM", - "TXhQk442CCGLydh6cfyfqvM6yJanEGeQj1", - "TKktQcbjXsXZDKPYLvUm8sxox2cT83g5rP", - "TBQUhYhdQpMRksBGAbpbTWSiE7WkGgy3Km", - "TALf34yjuLZjF1WQqCaUkf73X8WbhfiEyM", - "TCGp3JAFM5vQZpsdNiKRTci7fVb7A2TPcu", - "TBExF3mNvnhmEFgHW4TmYXXdhevRchnQyb", - "TS8o6WcHroSnzWNt4AiserAuVkye5Msvcm", - "TBtMRD79NkLyAvMkCTTj5VC5KZnz2Po2XZ", - }; - int i = 1; - for (String ownerKey : witnessKey) { - String triggerString = "\"" + ownerKey - + "\"" + ", 20000000000"; - System.out.println(triggerString); - //dapp chain trc20 tract TXkdXbzjoLpxGAD2strP1zwjJzR6osNfD7 - byte[] contractAddress = PublicMethed.decode58Check("TXkdXbzjoLpxGAD2strP1zwjJzR6osNfD7"); - //main chain TRC 20 contract TCCcBZEdTHmS1NfFtCYfwpjBKeTv515n71 - //byte[] contractAddress = PublicMethed.decode58Check("TCCcBZEdTHmS1NfFtCYfwpjBKeTv515n71"); - - PublicMethed - .triggerContract(contractAddress, "transfer(address,uint256)", triggerString, false, - 0, 1000000000, "0", 0, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = PublicMethed.signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java deleted file mode 100644 index f4a97d2ba33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java +++ /dev/null @@ -1,169 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.ChainParameters; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TestApproveProposal { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testApproveProposal() { - HashMap proposalMap = new HashMap(); - //proposalMap.put(25L, 1L); - proposalMap.put(27L, 0L); - //proposalMap.put(28L, 1L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - try { - Thread.sleep(20000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - //Get proposal list after approve - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - //logger.info(Integer.toString(listProposals.get().getProposals(0).getApprovalsCount())); - - String[] witnessKey = { - - "369F095838EB6EED45D4F6312AF962D5B9DE52927DA9F04174EE49F9AF54BC77", - "9FD8E129DE181EA44C6129F727A6871440169568ADE002943EAD0E7A16D8EDAC", - - }; - byte[] witnessAddress; - for (String key : witnessKey) { - witnessAddress = PublicMethed.getFinalAddress(key); - PublicMethed.approveProposal(witnessAddress, key, proposalId, - true, blockingStubFull); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Test(enabled = true) - public void testGetChainParameters() { - //Set the default map - HashMap defaultCommitteeMap = new HashMap(); - defaultCommitteeMap.put("MAINTENANCE_TIME_INTERVAL", 300000L); - defaultCommitteeMap.put("ACCOUNT_UPGRADE_COST", 9999000000L); - defaultCommitteeMap.put("CREATE_ACCOUNT_FEE", 100000L); - defaultCommitteeMap.put("TRANSACTION_FEE", 10L); - defaultCommitteeMap.put("ASSET_ISSUE_FEE", 1024000000L); - defaultCommitteeMap.put("WITNESS_PAY_PER_BLOCK", 32000000L); - defaultCommitteeMap.put("WITNESS_STANDBY_ALLOWANCE", 115200000000L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT", 0L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_BANDWIDTH_RATE", 1L); - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info("Index is:" + i); - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java deleted file mode 100644 index db0de1d5b47..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TestExchangeTransaction { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testCreateShieldToken() { - String tokenOwnerKey = "2925e186bb1e88988855f11ebf20ea3a6e19ed92328b0ffb576122e769d45b68"; - byte[] tokenOwnerAddress = PublicMethed.getFinalAddress(tokenOwnerKey); - PublicMethed.printAddress(tokenOwnerKey); - Assert.assertTrue(PublicMethed.sendcoin(tokenOwnerAddress, 20480000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 1500000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - Assert.assertTrue(PublicMethed.createAssetIssue(tokenOwnerAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, tokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(tokenOwnerAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - - - } - - @Test(enabled = true, threadPoolSize = 20, invocationCount = 20) - public void testExchangeTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeAddress = ecKey1.getAddress(); - String exchangeKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] transactionAddress = ecKey2.getAddress(); - String transactionKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchangeKey); - PublicMethed.printAddress(transactionKey); - - Assert.assertTrue(PublicMethed.sendcoin(exchangeAddress, 1500000000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(transactionAddress, 1500000000000000L, fromAddress, - testKey002, blockingStubFull)); - Long totalSupply = 1500000000000000L; - Random rand = new Random(); - Integer randNum = rand.nextInt(900000000) + 1; - String name = "exchange_" + Long.toString(randNum); - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - Assert.assertTrue(PublicMethed.createAssetIssue(exchangeAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 100000000L, 10000000000L, - 10L, 10L, exchangeKey, blockingStubFull)); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Assert.assertTrue(PublicMethed.transferAsset(transactionAddress, name.getBytes(), - 1500000000L, exchangeAddress, exchangeKey, blockingStubFull)); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //500000000000000L //5000000L - Assert.assertTrue(PublicMethed.exchangeCreate(name.getBytes(), 500000000000000L, - TRX_SYMBOL_BYTES, 500000000000000L, exchangeAddress, exchangeKey, blockingStubFull)); - try { - Thread.sleep(300000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Integer i = 0; - while (i++ < 10000) { - PublicMethed.exchangeTransaction(exchangeId, TRX_SYMBOL_BYTES, 100000, 99, - transactionAddress, transactionKey, blockingStubFull); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - PublicMethed.exchangeTransaction(exchangeId, name.getBytes(), 100000, 1, - transactionAddress, transactionKey, blockingStubFull); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java deleted file mode 100644 index efee959ba63..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java +++ /dev/null @@ -1,183 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -//import java.io.FileWriter; -//import java.io.BufferedWriter; - - -@Slf4j -public class TestMapBigLongAndNumbers { - - //testng001、testng002、testng003、testng004 - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - //private final String testAddress41 = ByteArray.toHexString(fromAddress); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - //Integer consumeUserResourcePercent = 20; - Integer consumeUserResourcePercent = 100; - String txid = ""; - Optional infoById = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void deployErc721KittyCore() { - - Long maxFeeLimit = 1000000000L; - - String contractName = "MappingExample"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestMapBigLongAndNumbers_deployErc721KittyCore"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestMapBigLongAndNumbers_deployErc721KittyCore"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, testKey002, - fromAddress, blockingStubFull); - - String data1 = "a"; - String data2 = "b"; - String data3 = "c"; - String data4 = "d"; - - for (int i = 0; i < 13; i++) { - data1 += data1; - } - - for (int i = 0; i < 12; i++) { - data2 += data2; - } - for (int i = 0; i < 11; i++) { - data3 += data3; - } - for (int i = 0; i < 10; i++) { - data4 += data4; - } - String data; - data = data1 + data2 + data3 + data4; - - String data5 = "a"; - - Account account = PublicMethed.queryAccountByAddress(fromAddress, blockingStubFull); - System.out.println(Long.toString(account.getBalance())); - long accountBalance = account.getBalance(); - - Random random = new Random(); - int randNumber = random.nextInt(15) + 15; - - System.out.println("random number:" + randNumber); - - try { - Thread.sleep(randNumber); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - for (int ii = 1; ii < 111100000; ii++) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] userAddress = ecKey1.getAddress(); - String inputKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String addresstest = Base58.encode58Check(userAddress); - - String saleContractString = "\"" + data + "\"" + "," + "\"" - + Base58.encode58Check(userAddress) + "\""; - - System.out.println("long string address:" + addresstest); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "update2(string,address)", - saleContractString, false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - logger.info(txid); - - String saleContractString1 = "\"" + data5 + "\"" + "," + "\"" - + Base58.encode58Check(userAddress) + "\""; - - System.out.println("short string address:" + addresstest); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "update2(string,address)", - saleContractString1, false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - logger.info(txid); - - System.out.println("time out"); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "testUseCpu(uint256)", - "1000000000", false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - infoById.get().getResultValue(); - - String isSuccess; - - if (infoById.get().getResultValue() == 0) { - logger.info("success:" + " Number:" + ii); - isSuccess = "success"; - } else { - logger.info("failed" + " Number:" + ii); - isSuccess = "fail"; - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java deleted file mode 100644 index 7f0382b2681..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java +++ /dev/null @@ -1,146 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class TestMutiSignStress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void testMutiSignForAccount() { - PublicMethed.printAddress(testKey002); - - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 9968981537400L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String[] permissionKeyString = new String[3]; - permissionKeyString[0] = manager1Key; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - permissionKeyString[1] = manager2Key; - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - permissionKeyString[2] = ownerKey; - String[] ownerKeyString = new String[1]; - ownerKeyString[0] = ownerKey; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - //permissionKeyString[0] = ownerKey; - - String[] ownerKeyString1 = new String[3]; - ownerKeyString1[0] = ownerKey; - ownerKeyString1[1] = manager1Key; - ownerKeyString1[2] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Integer i = 0; - while (i++ <= 1000) { - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - PublicMethed.printAddress(newKey); - - PublicMethedForMutiSign.sendcoin( - newAddress, 4000000L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalance( - ownerAddress, 1000000L, 0, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalanceGetEnergy( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalanceForReceiver( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, null, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, newAddress, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.updateAccount( - ownerAddress, Long.toString(System.currentTimeMillis()).getBytes(), ownerKey, - blockingStubFull, ownerKeyString1); - } - - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java deleted file mode 100644 index 8af17ca172f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java +++ /dev/null @@ -1,389 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestNetErc721Cat { - - //testng001、testng002、testng003、testng004 - //testng001、testng002、testng003、testng004 - private final String testKey002 = - //"7306c6044ad7c03709980aa188b8555288b7e0608f5edbf76ff2381c5a7a15a8"; - //"3a54ba30e3ee41b602eca8fb3a3ca1f99f49a3d3ab5d8d646a2ccdd3ffd9c21d"; - //fromAddress - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - Integer consumeUserResourcePercent = 20; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(deployKey); - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(triggerAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(deployAddress, 100000000L, - 3, 1, deployKey, blockingStubFull)); - /* Assert.assertTrue(PublicMethed.freezeBalanceGetCpu(triggerAddress,100000000L, - 3,1,triggerKey,blockingStubFull));*/ - /*Assert.assertTrue(PublicMethed.buyStorage(500000000L,deployAddress,deployKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.buyStorage(500000000L,triggerAddress,triggerKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(deployAddress,100000000L,3, - deployKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(triggerAddress,100000000L,3, - triggerKey,blockingStubFull));*/ - - } - - @Test(enabled = false) - public void deployErc721KittyCore() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployAddress, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "KittyCore"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deployErc721KittyCore"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deployErc721KittyCore"); - logger.info("Kitty Core"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(kittyCoreContractAddress, - blockingStubFull); - - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress).substring(2)); - - kittyCoreAddressAndCut = "000000000000000000000000" + ByteArray - .toHexString(kittyCoreContractAddress).substring(2); - kittyCoreAddressAndCut = kittyCoreAddressAndCut + "0000000000000000000000000000000000000000000" - + "000000000000000000100"; - } - - @Test(enabled = false) - public void deploySaleClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "SaleClockAuction"; - logger.info("Sale Clock Auction"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deploySaleClockAuction"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deploySaleClockAuction"); - saleClockAuctionContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(saleClockAuctionContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void deploySiringClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "SiringClockAuction"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deploySiringClockAuction"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deploySiringClockAuction"); - logger.info("Siring Clock Auction"); - siringClockAuctionContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(siringClockAuctionContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void deployGeneScienceInterface() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "GeneScienceInterface"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deployGeneScienceInterface"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deployGeneScienceInterface"); - logger.info("gene Science Interface"); - geneScienceInterfaceContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, consumeUserResourcePercent, null, deployKey, deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(geneScienceInterfaceContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void triggerToSetThreeContractAddressToKittyCore() { - //Set SaleAuctionAddress to kitty core. - String saleContractString = "\"" + Base58.encode58Check(saleClockAuctionContractAddress) + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "setSaleAuctionAddress(address)", - saleContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(siringClockAuctionContractAddress) - + "\""; - txid = PublicMethed - .triggerContract(kittyCoreContractAddress, "setSiringAuctionAddress(address)", - siringContractString, false, 0, 10000000L, - deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Set gen contract to kitty core - String genContractString = "\"" + Base58.encode58Check(geneScienceInterfaceContractAddress) - + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setGeneScienceAddress(address)", genContractString, - false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Start the game. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "unpause()", "", false, 0, - 10000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("start the game " + txid); - - //Create one gen0 cat. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "-1000000000000000", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "gen0CreatedCount()", "#", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - /* txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "name()","#",false,0,10000000,triggerAddress, - triggerKey,blockingStubFull); - logger.info("getname " + txid);*/ - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "getKitty(uint256)", "1", false, 0, 10000000, triggerAddress, - triggerKey, blockingStubFull); - logger.info("getKitty " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String newCxoAddress = "\"" + Base58.encode58Check(triggerAddress) - + "\""; - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("COO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CFO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, 1000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CEO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) - public void unCreateKitty() { - Integer times = 0; - logger.info("In create kitty, kitty core address is " + ByteArray - .toHexString(kittyCoreContractAddress)); - while (times++ < 20) { - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerAddress, triggerKey, blockingStubFull); - logger.info("createGen0 " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getResultValue() == 0); - /* String promoKitty = "\"" + times.toString() + "\",\"" - + Base58.encode58Check(kittyCoreContractAddress) + "\""; - logger.info(promoKitty); - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createPromoKitty(uint256,address)", promoKitty,false, - 0,10000000L,triggerAddress,triggerKey,blockingStubFull); - logger.info("createPromoKitty " + txid); - infoById = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0);*/ - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java deleted file mode 100644 index 9c84ac0bf96..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import static stest.tron.wallet.common.client.utils.PublicMethed.getTransactionInfoById; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestNetFomo3D { - - //testng001、testng002、testng003、testng004 - private final String testNetAccountKey = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - //"BC70ADC5A0971BA3F7871FBB7249E345D84CE7E5458828BE1E28BF8F98F2795B"; - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - Optional infoById = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testNetAccountKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - //Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(testNetAccountAddress,10000000L, - //3,1,testNetAccountKey,blockingStubFull)); - /* Assert.assertTrue(PublicMethed.buyStorage(50000000L,testNetAccountAddress, - testNetAccountKey, - blockingStubFull));*/ - - } - - @Test(enabled = false) - public void deployErc721CryptoKitties() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testNetAccountAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "Fomo3D"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetFomo3D_deployErc721CryptoKitties"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetFomo3D_deployErc721CryptoKitties"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testNetAccountKey, testNetAccountAddress, blockingStubFull); - - String code1 = Configuration.getByPath("testng.conf") - .getString("code.code1_TestNetFomo3D_deployErc721CryptoKitties"); - String abi1 = Configuration.getByPath("testng.conf") - .getString("abi.abi1_TestNetFomo3D_deployErc721CryptoKitties"); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi1, - code1, "", maxFeeLimit, 0L, 100, null, - testNetAccountKey, testNetAccountAddress, blockingStubFull); - - final SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - accountResource = PublicMethed.getAccountResource(testNetAccountAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - //Assert.assertTrue(storageUsage > 0); - //Assert.assertTrue(storageLimit > 0); - Assert.assertTrue(cpuLimit > 0); - Assert.assertTrue(cpuUsage > 0); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - //logger.info(smartContract.getName()); - //logger.info(smartContract.getAbi().toString()); - - } - - @Test(enabled = false) - public void tooLargeStorage() throws IOException { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testNetAccountAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - Long maxFeeLimit = 100000000000000000L; - String contractName = "tooLargeStorage"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetFomo3D_tooLargeStorage"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetFomo3D_tooLargeStorage"); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, - code, "", maxFeeLimit, 0L, 100, null, - testNetAccountKey, testNetAccountAddress, blockingStubFull); - infoById = getTransactionInfoById(txid, blockingStubFull); - accountResource = PublicMethed.getAccountResource(testNetAccountAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - - /* String name = readFromXieChang();*/ - String stringTimes = Integer.toString(7); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - txid = PublicMethed.triggerContract(contractAddress, "slice(uint256)", stringTimes, false, - 0, maxFeeLimit, testNetAccountAddress, testNetAccountKey, blockingStubFull); - logger.info("slice " + txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - infoById = getTransactionInfoById(txid, blockingStubFull); - - txid = PublicMethed.triggerContract(contractAddress, "s()", "#", false, - 0, maxFeeLimit, testNetAccountAddress, testNetAccountKey, blockingStubFull); - logger.info(txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public String readFromXieChang() throws IOException { - File file = new File( - "/Users/wangzihe/Desktop/ddd.txt"); - FileReader reader = null; - try { - reader = new FileReader(file); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - BufferedReader reAder = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - while ((s = reAder.readLine()) != null) { - sb.append(s); - } - - String code = sb.toString(); - reAder.close(); - return code; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java deleted file mode 100644 index ece70cb9ccf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java +++ /dev/null @@ -1,43 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.Test; -import org.tron.common.utils.ByteArray; - -@Slf4j -public class TestOperations { - - @Test(enabled = true) - public void test002() { - //指定需要支持的合约id(查看proto中Transaction.ContractType定义), - // 这里包含除AccountPermissionUpdateContract(id=46)以外的所有合约 - Integer[] contractId = {0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 30, 31, 33, - 41, 42, 43, 44, 45, 48, 49}; - List list = new ArrayList<>(Arrays.asList(contractId)); - byte[] operations = new byte[32]; - list.forEach(e -> { - operations[e / 8] |= (1 << e % 8); - }); - //77ff07c0023e0300000000000000000000000000000000000000000000000000 - logger.info(ByteArray.toHexString(operations)); - } - - @Test(enabled = true) - public void test003() { - String operations = "77ff07c0023e0300000000000000000000000000000000000000000000000000"; - List contractId = new ArrayList<>(); - for (int i = 0; i < operations.length(); i = i + 2) { - int operation16 = Integer.valueOf(operations.substring(i, i + 2), 16); - for (int n = 0; n < 8; n++) { - int tmp = 1 << n; - if ((tmp & operation16) == tmp) { - contractId.add(i * 4 + n); - } - } - } - logger.info(contractId.toString()); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java deleted file mode 100644 index 458daa381b4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; - -@Slf4j -public class TestStorageAndCpu { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = "47.94.243.150:50051"; - private String fullnode1 = "47.94.243.150:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void scanBlock() { - Long startNum = 26165658L; - Long endNum = 26166320L; - Integer totalNum = 0; - Integer successNum = 0; - Integer failedNum = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (startNum <= endNum) { - logger.info("scan block num:" + startNum); - builder.setNum(startNum); - List transactionList = blockingStubFull - .getBlockByNum(builder.build()).getTransactionsList(); - Integer transactionNumInThisBlock = transactionList.size(); - totalNum = totalNum + transactionNumInThisBlock; - for (Transaction transaction : transactionList) { - if (transaction.getRet(0).getContractRet().name().equals("SUCCESS")) { - successNum++; - } else { - failedNum++; - logger.info(transaction.getRet(0).getContractRet().name()); - } - } - startNum++; - } - logger.info("successNum:" + successNum); - logger.info("failedNum:" + failedNum); - logger.info("totalNum:" + totalNum); - logger.info("Success rate:" + (double)failedNum / (double)totalNum); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void storageAndCpu() { - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - PublicMethed - .freezeBalanceGetEnergy(fromAddress, 1000000000000L, 3, 1, testKey002, blockingStubFull); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKey002, fromAddress, blockingStubFull); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - String txid; - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - - Integer i = 1; - while (i++ < 8000) { - String initParmes = "\"" + "930" + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "9100", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress, - "storage8Char()", "", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - //storage 9 EnergyUsageTotal is 211533, 10 is 236674, 5 is 110969,21 is 500000 - txid = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", "21", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - //logger.info("i is " +Integer.toString(i) + " " + txid); - //txidList.add(txid); - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (i % 10 == 0) { - chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - getChainParameters = Optional.ofNullable(chainParameters); - logger.info(getChainParameters.get().getChainParameter(22).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(22).getValue())); - logger.info(getChainParameters.get().getChainParameter(23).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(23).getValue())); - - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - /* - afterTime = System.currentTimeMillis(); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock.getBlockHeader().getRawData().getNumber() + 2; - Long blockNum = beforeBlockNum; - Integer txsNum = 0; - Integer topNum = 0; - Integer totalNum = 0; - Long energyTotal = 0L; - String findOneTxid = ""; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (blockNum <= afterBlockNum) { - builder.setNum(blockNum); - txsNum = blockingStubFull1.getBlockByNum(builder.build()).getTransactionsCount(); - totalNum = totalNum + txsNum; - if (topNum < txsNum) { - topNum = txsNum; - findOneTxid = ByteArray.toHexString(Sha256Hash.hash(blockingStubFull1 - .getBlockByNum(builder.build()).getTransactionsList().get(2) - .getRawData().toByteArray())); - //logger.info("find one txid is " + findOneTxid); - } - - blockNum++; - } - Long costTime = (afterTime - beforeTime - 31000) / 1000; - logger.info("Duration block num is " + (afterBlockNum - beforeBlockNum - 11)); - logger.info("Cost time are " + costTime); - logger.info("Top block txs num is " + topNum); - logger.info("Total transaction is " + (totalNum - 30)); - logger.info("Average Tps is " + (totalNum / costTime)); - - infoById = PublicMethed.getTransactionInfoById(findOneTxid, blockingStubFull1); - Long oneEnergyTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("EnergyTotal is " + oneEnergyTotal); - logger.info("Average energy is " + oneEnergyTotal * (totalNum / costTime)); -*/ - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java deleted file mode 100644 index 628b2843d8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java +++ /dev/null @@ -1,324 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestTransferTokenInContract { - - private static final long TotalSupply = 1000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private AtomicLong count = new AtomicLong(); - private AtomicLong errorCount = new AtomicLong(); - private long startTime = System.currentTimeMillis(); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - /** - * constructor. - */ - - public ByteString createAssetissue(byte[] devAddress, String devKey, String tokenName) { - - ByteString assetAccountId = null; - ByteString addressBS1 = ByteString.copyFrom(devAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - logger.info("The token name: " + tokenName); - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(devAddress, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, devKey, blockingStubFull)); - - Account getAssetIdFromThisAccount = PublicMethed.queryAccount(devAddress, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - tokenName = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0) - .getName().toByteArray()); - } - return assetAccountId; - } - - @Test(enabled = true, threadPoolSize = 2, invocationCount = 2) - public void continueRun() { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - - String tokenName = "testAI_" + randomInt(10000, 90000); - ByteString tokenId = createAssetissue(user001Address, user001Key, tokenName); - - // devAddress transfer token to A - PublicMethed.transferAsset(dev001Address, tokenId.toByteArray(), 101, user001Address, - user001Key, blockingStubFull); - - // deploy transferTokenContract - String contractName = "transferTokenContract"; - String code = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000" - + "000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080" - + "fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b604051" - + "73ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8a" - + "d094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a723058200ba246bdb58b" - + "e0f221ad07e1b19de843ab541150b329ddd01558c2f1cefe1e270029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}]," - + "\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\"" - + ":\"payable\",\"type\":\"constructor\"}]"; - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, tokenId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy receiveTokenContract - contractName = "recieveTokenContract"; - code = "60806040526000805560c5806100166000396000f30060806040526004361060485763ffffffff7c0100000" - + "00000000000000000000000000000000000000000000000000060003504166362548c7b8114604a578063890" - + "eba68146050575b005b6048608c565b348015605b57600080fd5b50d38015606757600080fd5b50d28015607" - + "357600080fd5b50607a6093565b60408051918252519081900360200190f35b6001600055565b60005481560" - + "0a165627a7a723058204c4f1bb8eca0c4f1678cc7cc1179e03d99da2a980e6792feebe4d55c89c022830029"; - abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"setFlag\",\"outputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[]," - + "\"name\":\"flag\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"fallback\"}]"; - byte[] receiveTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy tokenBalanceContract - contractName = "tokenBalanceContract"; - code = "608060405260ff806100126000396000f30060806040526004361060485763ffffffff7c010000000000000" - + "0000000000000000000000000000000000000000000600035041663a730416e8114604d578063b69ef8a8146" - + "081575b600080fd5b606f73ffffffffffffffffffffffffffffffffffffffff6004351660243560ab565b604" - + "08051918252519081900360200190f35b348015608c57600080fd5b50d38015609857600080fd5b50d280156" - + "0a457600080fd5b50606f60cd565b73ffffffffffffffffffffffffffffffffffffffff90911690d16000908" - + "15590565b600054815600a165627a7a723058202b6235122df66c062c2e723ad58a9fea93346f3bc19898971" - + "8f211aa1dbd2d7a0029"; - abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":" - + "[{\"name\":\"b\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":" - + "\"balance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - byte[] tokenBalanceContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed.transferAsset(user001Address, tokenId.toByteArray(), 100, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - for (int i = 0; i < 1000000000000L; i++) { - logger.info("** This is " + i + "times --------------------------------------------"); - count.getAndAdd(4); - if (count.get() % 500 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - PublicMethed.freezeBalanceForReceiver(user001Address, - PublicMethed.getFreezeBalanceCount(user001Address, - user001Key, 300000L, blockingStubFull), 0, - 1, ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - PublicMethed.freezeBalanceForReceiver(user001Address, 10_000_000L, - 0, 0, ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(receiveTokenContractAddress) + "\",\"" + tokenId - .toStringUtf8() - + "\",\"5\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, tokenId.toStringUtf8(), - 10, user001Address, user001Key, - blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - // user trigger A to transfer token to devAddress - param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId.toStringUtf8() - + "\",\"5\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - // user trigger C to get B's token balance - param = - "\"" + Base58.encode58Check(receiveTokenContractAddress) + "\",\"" + tokenId - .toStringUtf8() - + "\""; - - triggerTxid = PublicMethed - .triggerContract(tokenBalanceContractAddress, "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - PublicMethed.triggerContract(tokenBalanceContractAddress, "balance()", - "#", false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - // user trigger C to get devAddress's token balance - param = "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId.toStringUtf8() + "\""; - - triggerTxid = PublicMethed - .triggerContract(tokenBalanceContractAddress, "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - PublicMethed.triggerContract(tokenBalanceContractAddress, "balance()", - "#", false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.unFreezeBalance(fromAddress, user001Key, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, user001Key, 0, - user001Address, blockingStubFull); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java deleted file mode 100644 index c14e596e378..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java +++ /dev/null @@ -1,52 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.crypto.SignUtils; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Sha256Hash; - -public class TransactionCheck { - - @Test - public void hexToTransaction() throws Exception { - String targetHex1 = ""; - String targetHex2 = ""; - String hex = targetHex1; - org.tron.protos.Protocol.Transaction transaction = org.tron.protos.Protocol.Transaction - .parseFrom(ByteArray.fromHexString(hex)); - getBase64FromByteString(transaction.getSignature(0)); - String base64 = getBase64FromByteString(transaction.getSignature(0)); - byte[] address = SignUtils - .signatureToAddress((Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())), base64, - CommonParameter.getInstance().isECKeyCryptoEngine()); - String addressStr = WalletClient.encode58Check(address); - String data = String.valueOf(transaction.getRawData().getData().toStringUtf8()); - System.out.println(addressStr); - System.out.println(data); - } - - - /** - * constructor. - */ - public static String getBase64FromByteString(ByteString sign) { - byte[] r = sign.substring(0, 32).toByteArray(); - byte[] s = sign.substring(32, 64).toByteArray(); - byte v = sign.byteAt(64); - if (v < 27) { - v += 27; //revId -> v - } - ECDSASignature signature = ECDSASignature.fromComponents(r, s, v); - return signature.toBase64(); - } - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java deleted file mode 100644 index 68924eb6d56..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java +++ /dev/null @@ -1,268 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DiversifierMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PaymentAddressMessage; -import org.tron.api.GrpcAPI.ViewingKeyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenTokenStress { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 1 * zenTokenFee + 1; - private Long sendTokenAmount = 1 * zenTokenFee; - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = true, threadPoolSize = 3, invocationCount = 3) - public void test1Shield2ShieldTransaction() throws InterruptedException { - List shieldOutList = new ArrayList<>(); - Integer times = 0; - Optional sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "7"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - while (times++ < 10000) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - - PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - zenTokenFee * 2, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - memo = times + ":shield note number"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.sendShieldCoin(zenTokenOwnerAddress, 2 * zenTokenFee, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull); - /* logger.info("Note number:" - + PublicMethed.getShieldNotesCount(sendShieldAddressInfo,blockingStubFull));*/ - } - - - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void test2Shield2ShieldTransaction() throws InterruptedException { - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - - Integer times = 0; - while (times++ < 10000) { - sk = blockingStubFull.getSpendingKey(EmptyMessage.newBuilder().build()); - //logger.info("sk: " + ByteArray.toHexString(sk.getValue().toByteArray())); - - diversifierMessage1 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d1: " + ByteArray.toHexString(diversifierMessage1.getD().toByteArray())); - diversifierMessage2 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d2: " + ByteArray.toHexString(diversifierMessage2.getD().toByteArray())); - diversifierMessage3 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d3: " + ByteArray.toHexString(diversifierMessage3.getD().toByteArray())); - - expandedSpendingKeyMessage = blockingStubFull.getExpandedSpendingKey(sk); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.getAsk()); - ak = blockingStubFull.getAkFromAsk(askBuilder.build()); - //logger.info("ak: " + ByteArray.toHexString(ak.getValue().toByteArray())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.getNsk()); - nk = blockingStubFull.getNkFromNsk(nskBuilder.build()); - //logger.info("nk: " + ByteArray.toHexString(nk.getValue().toByteArray())); - - ViewingKeyMessage.Builder viewBuilder = ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.getValue()); - viewBuilder.setNk(nk.getValue()); - ivk = blockingStubFull.getIncomingViewingKey(viewBuilder.build()); - //logger.info("ivk: " + ByteArray.toHexString(ivk.getIvk().toByteArray())); - - IncomingViewingKeyDiversifierMessage.Builder builder = - IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage1); - builder.setIvk(ivk); - PaymentAddressMessage addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address1: " + addressMessage.getPaymentAddress()); - addressInfo1.setSk(sk.getValue().toByteArray()); - addressInfo1.setD(new DiversifierT(diversifierMessage1.getD().toByteArray())); - addressInfo1.setIvk(ivk.getIvk().toByteArray()); - addressInfo1.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo1.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo1 = Optional.of(addressInfo1); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage2); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address2: " + addressMessage.getPaymentAddress()); - addressInfo2.setSk(sk.getValue().toByteArray()); - addressInfo2.setD(new DiversifierT(diversifierMessage2.getD().toByteArray())); - addressInfo2.setIvk(ivk.getIvk().toByteArray()); - addressInfo2.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo2.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo2 = Optional.of(addressInfo2); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage3); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address3: " + addressMessage.getPaymentAddress()); - addressInfo3.setSk(sk.getValue().toByteArray()); - addressInfo3.setD(new DiversifierT(diversifierMessage3.getD().toByteArray())); - addressInfo3.setIvk(ivk.getIvk().toByteArray()); - addressInfo3.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo3.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo3 = Optional.of(addressInfo3); - } - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java b/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java deleted file mode 100644 index 2a81c673f23..00000000000 --- a/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.other; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class deployMainGateway { - - - private final String testDepositTrx = "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096" - + "c6bacb7"; - private final byte[] testDepositAddress = PublicMethed.getFinalAddress(testDepositTrx); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] depositAddress = ecKey1.getAddress(); - String testKeyFordeposit = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy Main Chain Gateway") - public void test1DepositTrc20001() { - - PublicMethed.printAddress(testKeyFordeposit); - - Assert.assertTrue(PublicMethed - .sendcoin(depositAddress, 1000_000_000L, testDepositAddress, testDepositTrx, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account accountOralce = PublicMethed.queryAccount(depositAddress, blockingStubFull); - long OralceBalance = accountOralce.getBalance(); - logger.info("OralceBalance: " + OralceBalance); - - String contractName = "gateWayContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_MainGateway"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_MainGateway"); - String parame = "\"" + Base58.encode58Check(testDepositAddress) + "\""; - - String deployTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address)", - parame, "", - maxFeeLimit, - 0L, 100, null, testKeyFordeposit, depositAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - byte[] mainChainGateway = infoById.get().getContractAddress().toByteArray(); - String mainChainGatewayAddress = WalletClient.encode58Check(mainChainGateway); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertNotNull(mainChainGateway); - - SmartContract smartContract = PublicMethed.getContract(mainChainGateway, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String outputPath = "./src/test/resources/mainChainGatewayAddress"; - try { - File mainChainFile = new File(outputPath); - Boolean cun = mainChainFile.createNewFile(); - FileWriter writer = new FileWriter(mainChainFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(mainChainGatewayAddress); - - out.close(); - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java b/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java deleted file mode 100644 index 90b3266b149..00000000000 --- a/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.other; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class deploySideGateway { - - - private final String testDepositTrx = "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096" - + "c6bacb7"; - private final byte[] testDepositAddress = PublicMethed.getFinalAddress(testDepositTrx); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] depositAddress = ecKey1.getAddress(); - String testKeyFordeposit = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = "127.0.0.1:50151"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy Side Chain Gateway") - public void test1DepositTrc20001() { - - PublicMethed.printAddress(testKeyFordeposit); - - String contractName = "gateWaysidechainContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_SideGateway"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_SideGateway"); - String parame = "\"" + Base58.encode58Check(testDepositAddress) + "\""; - - String deployTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address)", - parame, "", - maxFeeLimit, - 0L, 100, null, testKeyFordeposit, depositAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - byte[] mainChainGateway = infoById.get().getContractAddress().toByteArray(); - String mainChainGatewayAddress = WalletClient.encode58Check(mainChainGateway); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertNotNull(mainChainGateway); - - SmartContract smartContract = PublicMethed.getContract(mainChainGateway, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String outputPath = "./src/test/resources/sideChainGatewayAddress"; - try { - File mainChainFile = new File(outputPath); - Boolean cun = mainChainFile.createNewFile(); - FileWriter writer = new FileWriter(mainChainFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(mainChainGatewayAddress); - - out.close(); - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java deleted file mode 100644 index e8b3d3acfe5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java +++ /dev/null @@ -1,320 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestTransfer001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //send account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //receipt account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] receiptAccountAddress = ecKey2.getAddress(); - String receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test - public void testSendCoin() { - //send account - ecKey1 = new ECKey(Utils.getRandom()); - final byte[] sendAccountAddress = ecKey1.getAddress(); - sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - //receipt account - ecKey2 = new ECKey(Utils.getRandom()); - final byte[] receiptAccountAddress = ecKey2.getAddress(); - receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull)); - - logger.info(receiptAccountKey); - //Test send coin. - Account sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountBeforeBalance = sendAccount.getBalance(); - Assert.assertTrue(sendAccountBeforeBalance == 90000000000L); - Account receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountBeforeBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountBeforeBalance == 0); - - //Test send coin - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.sendcoin(receiptAccountAddress, 49880000000L, - sendAccountAddress, sendAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance)); - Assert.assertTrue(sendAccountAfterBalance == 90000000000L - 49880000000L - 100000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance = receiptAccount.getBalance(); - logger.info(Long.toString(receiptAccountAfterBalance)); - Assert.assertTrue(receiptAccountAfterBalance == 49880000000L); - - //Send coin failed due to no enough balance. - Assert.assertFalse(sendcoin(toAddress, 9199999999999999999L, fromAddress, testKey002)); - //Send coin failed due to the amount is 0. - Assert.assertFalse(sendcoin(toAddress, 0L, fromAddress, testKey002)); - //Send coin failed due to the amount is -1Trx. - Assert.assertFalse(sendcoin(toAddress, -1000000L, fromAddress, testKey002)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java deleted file mode 100644 index 3c6435ee193..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java +++ /dev/null @@ -1,389 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "transaction007_" + Long.toString(now); - private static Protocol.Transaction sendCoinTransaction; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final Long createUseFee = 100000L; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendCoinAddress = ecKey1.getAddress(); - String testKeyForSendCoin = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String testKeyForNewAccount = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - private static Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static Protocol.Transaction sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return transaction; - } - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(testKeyForSendCoin); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = true) - public void test1UseFeeOrNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - sendCoinAddress = ecKey1.getAddress(); - testKeyForSendCoin = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - newAccountAddress = ecKey2.getAddress(); - testKeyForNewAccount = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(sendCoinAddress, 200000L, - fromAddress, testKey002, blockingStubFull)); - Long feeNum = 0L; - Long netNum = 0L; - Long sendNum = 0L; - Long feeCost = 0L; - Long times = 0L; - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long beforeBalance = sendAccountInfo.getBalance(); - Long netUsed1 = 0L; - Long netUsed2 = 1L; - logger.info("Before test, the account balance is " + Long.toString(beforeBalance)); - - while (!(netUsed1.equals(netUsed2))) { - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - netUsed1 = sendAccountInfo.getFreeNetUsage(); - sendCoinTransaction = sendcoin(fromAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - netUsed2 = sendAccountInfo.getFreeNetUsage(); - - if (times++ < 1) { - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - logger.info("solidity block num is " + Long.toString(getTransactionById - .get().getBlockNumber())); - Assert.assertTrue(getTransactionById.get().getBlockNumber() > 0); - } - - logger.info(Long.toString(netUsed1)); - logger.info(Long.toString(netUsed2)); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - Assert.assertTrue(netUsed2 > 4500); - //Next time, use fee - sendCoinTransaction = sendcoin(fromAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - logger.info(getTransactionById.get().toString()); - logger.info("when use fee, the block num is " + Long.toString(getTransactionById - .get().getBlockNumber())); - Assert.assertTrue(getTransactionById.get().getFee() > 0); - Assert.assertTrue(getTransactionById.get().getBlockNumber() > 0); - } - - @Test(enabled = true) - public void test2CreateAccountUseFee() { - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long beforeBalance = sendAccountInfo.getBalance(); - logger.info("before balance " + Long.toString(beforeBalance)); - Long times = 0L; - sendCoinTransaction = sendcoin(newAccountAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - - logger.info("In create account case, the fee is " + getTransactionById.get().getFee()); - Assert.assertTrue(getTransactionById.get().getFee() == createUseFee); - - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long afterBalance = sendAccountInfo.getBalance(); - logger.info("after balance " + Long.toString(afterBalance)); - Assert.assertTrue(afterBalance + 1L + createUseFee == beforeBalance); - } - - @Test(enabled = true) - public void test3InvalidGetTransactionById() { - String txId = ""; - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - Optional getTransactionById = Optional.ofNullable(transaction); - Assert.assertTrue(getTransactionById.get().getRawData().getContractCount() == 0); - - txId = "1"; - bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - request = BytesMessage.newBuilder().setValue(bsTxid).build(); - transaction = blockingStubFull.getTransactionById(request); - getTransactionById = Optional.ofNullable(transaction); - Assert.assertTrue(getTransactionById.get().getRawData().getContractCount() == 0); - } - - @Test(enabled = true) - public void test4NoBalanceCanSend() { - Long feeNum = 0L; - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - Long beforeBalance = sendAccountInfo.getBalance(); - logger.info("Before test, the account balance is " + Long.toString(beforeBalance)); - while (feeNum < 250) { - sendCoinTransaction = sendcoin(fromAddress, 10L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - feeNum++; - } - Assert.assertTrue(PublicMethed.waitProduceNextBlock(blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - /** - * constructor. - */ - - public Protocol.Transaction updateAccount(byte[] addressBytes, byte[] accountNameBytes, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return transaction; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java deleted file mode 100644 index 181328d0f0f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java +++ /dev/null @@ -1,288 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer004 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /* @Test(enabled = true) - public void testGetTransactionsByTimestamp() { - long start = now - 16400000; - long end = now; - GrpcAPI.TimeMessage.Builder timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - TimePaginatedMessage.Builder timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - TransactionList transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - Optional gettransactionbytimestamp = Optional - .ofNullable(transactionList); - - if (gettransactionbytimestamp.get().getTransactionCount() == 0) { - logger.info("Last one day there is no transfaction,please test for manual!!!"); - } - - Assert.assertTrue(gettransactionbytimestamp.isPresent()); - logger.info(Integer.toString(gettransactionbytimestamp.get().getTransactionCount())); - for (Integer j = 0; j < gettransactionbytimestamp.get().getTransactionCount(); j++) { - Assert.assertTrue(gettransactionbytimestamp.get().getTransaction(j).hasRawData()); - Assert.assertFalse(gettransactionbytimestamp.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = true) - public void testExceptionTimeToGetGetTransactionsByTimestamp() { - //Start time is below zero. - long start = -10000; - long end = -1; - GrpcAPI.TimeMessage.Builder timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - TimePaginatedMessage.Builder timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - TransactionList transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - Optional gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //Start time is equal with end time. - long now = System.currentTimeMillis(); - start = now; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //No transeration occured. - now = System.currentTimeMillis(); - start = now; - end = now + 1; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - - //Start time is late than currently time,no exception. - start = now + 1000000; - end = start + 1000000; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //Start time is late than the end time, no exception. - start = now; - end = now - 10000000; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //The offset is -1 - start = now - 10000000; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(-1); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //The setLimit is -1 - start = now - 10000000; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - - }*/ - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java deleted file mode 100644 index 3619db66a17..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestTransfer007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidityInFullnode = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - /* private String solidityInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1);*/ - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - /* channelSolidityInFullnode = ManagedChannelBuilder.forTarget(solidityInFullnode) - .usePlaintext(true) - .build(); - blockingStubSolidityInFullnode = WalletSolidityGrpc.newBlockingStub(channelSolidityInFullnode); - */ - } - - - @Test - public void testSendCoin() { - String transactionId = PublicMethed.sendcoinGetTransactionId(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionById(transactionId, blockingStubFull); - Long timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - Long timestamptispBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestamptispBlockOne); - } - - @Test - public void testSendCoin2() { - String transactionId = PublicMethed.sendcoinGetTransactionId(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionById(transactionId, blockingStubFull); - Long timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - Long timestampBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestampBlockOne); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - infoById = PublicMethed.getTransactionById(transactionId, blockingStubSolidity); - timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - timestampBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestampBlockOne); - - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(transactionId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - - transactionInfo = blockingStubSolidity.getTransactionInfoById(request); - Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - transactionInfo = blockingStubFull.getTransactionInfoById(request); - Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - //transactionInfo = blockingStubSolidityInFullnode.getTransactionInfoById(request); - //Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java b/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java deleted file mode 100644 index 72ee459aae1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java +++ /dev/null @@ -1,504 +0,0 @@ -package stest.tron.wallet.updateCompatibility; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class MutisignOperationerGodicTest { - - final String updateName = Long.toString(System.currentTimeMillis()); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] mutisignAccountAddress = ecKey3.getAddress(); - String mutisignAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private Long costTokenAmount = 8 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - @BeforeSuite - public void beforeSuite() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - if (PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getCreateTime() == 0) { - PublicMethed.sendcoin(foundationZenTokenAddress, 20480000000000L, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 15000000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - PublicMethed.createAssetIssue(foundationZenTokenAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - } - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(mutisignAccountAddress, 1000_000_000_000L, fromAddress, - testKey002, blockingStubFull)); - //updatepermission权限,账户交易所需钱等前置条件写在这 - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = manager1Key; - ownerKeyString[1] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, mutisignAccountAddress, mutisignAccountKey, - blockingStubFull, new String[]{mutisignAccountKey})); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true) - public void test001MutiSignGodicAccountTypeTransaction() { - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(("" + System.currentTimeMillis()).getBytes(), - mutisignAccountAddress, mutisignAccountKey, 2, blockingStubFull, - permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.createAccountWhtiPermissionId( - mutisignAccountAddress, newAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, mutisignAccountAddress, 2, - mutisignAccountKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 2, - mutisignAccountKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 1, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 0, - ByteString.copyFrom(newAddress), - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - mutisignAccountAddress, mutisignAccountKey, 0, null, - 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - mutisignAccountAddress, mutisignAccountKey, 0, newAddress, - 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - mutisignAccountAddress, updateName.getBytes(), mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - } - - @Test(enabled = true) - public void test002MutiSignGodicContractTypeTransaction() { - Long maxFeeLimit = 1000000000L; - //String contractName = "StorageAndCpu" + Integer.toString(randNum); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContractWithPermissionId( - contractName, abi, code, "", maxFeeLimit, - 0L, 100, maxFeeLimit, "0", 0L, null, - mutisignAccountKey, mutisignAccountAddress, blockingStubFull, permissionKeyString, 2); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContractWithPermissionId(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, "0", 0L, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, permissionKeyString, 2); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId( - contractAddress, 50, mutisignAccountKey, - mutisignAccountAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId( - contractAddress, 50, mutisignAccountKey, - mutisignAccountAddress, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, mutisignAccountAddress, mutisignAccountKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true) - public void test003MutiSignGodicTokenTypeTransaction() { - - long now = System.currentTimeMillis(); - String name = "MutiSign001_" + Long.toString(now); - long totalSupply = now; - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - Assert.assertTrue(PublicMethedForMutiSign - .createAssetIssueWithpermissionId(mutisignAccountAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Assert.assertTrue(PublicMethedForMutiSign.unFreezeAsset(mutisignAccountAddress, - // mutisignAccountKey,2,ownerKeyString,blockingStubFull)); - - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount( - mutisignAccountAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - - Assert.assertTrue(PublicMethedForMutiSign.transferAssetWithpermissionId(manager1Address, - assetAccountId1.toByteArray(), 10, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign - .updateAssetWithPermissionId(mutisignAccountAddress, description.getBytes(), url.getBytes(), - 100L, 100L, mutisignAccountKey, - 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true) - public void test004MutiSignGodicExchangeTypeTransaction() { - - ECKey ecKey22 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey22.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey22.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - - long now = System.currentTimeMillis(); - String name2 = "exchange001_2_" + Long.toString(now); - String name1 = "exchange001_1_" + Long.toString(now); - final long totalSupply = 1000000001L; - - org.junit.Assert - .assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - org.junit.Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(secondExchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - org.junit.Assert - .assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - org.junit.Assert.assertTrue(PublicMethed.transferAsset( - mutisignAccountAddress, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), 100, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), 200, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), 50, 1, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign.participateAssetIssueWithPermissionId( - secondExchange001Address, - assetAccountId2.toByteArray(), 1, mutisignAccountAddress, mutisignAccountKey, 2, - blockingStubFull, ownerKeyString)); - - } - - @Test(enabled = true) - public void test005MutiSignGodicShieldTransaction() { - - Assert.assertTrue(PublicMethed.transferAsset(mutisignAccountAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(mutisignAccountAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeBalance = PublicMethed - .queryAccount(mutisignAccountAddress, blockingStubFull).getBalance(); - final Long beforeNetUsed = PublicMethed - .getAccountResource(mutisignAccountAddress, blockingStubFull).getFreeNetUsed(); - - String memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethedForMutiSign.sendShieldCoin( - mutisignAccountAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true) - public void test006MutiSignGodicWitnessTransaction() { - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = manager1Key; - ownerKeyString[1] = manager2Key; - PublicMethed.printAddress(newKey); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethed.sendcoin(newAddress, 1000000_000_000L, fromAddress, - testKey002, blockingStubFull)); - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, newAddress, newKey, - blockingStubFull, new String[]{newKey})); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long now = System.currentTimeMillis(); - String url = "MutiSign001_" + Long.toString(now) + ".com"; - Assert.assertTrue(PublicMethedForMutiSign.createWitness(url, newAddress, - newKey, 2, permissionKeyString, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert - .assertTrue(PublicMethedForMutiSign.updateWitness2(newAddress, "newWitness.com".getBytes(), - newKey, 2, permissionKeyString, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String voteStr = Base58.encode58Check(newAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, mutisignAccountAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - - - } - - @Test(enabled = true) - public void test007MutiSignGodicProposalTypeTransaction() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(newAddress, newKey, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - newAddress, newKey, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - newAddress, newKey, proposalId, 2, blockingStubFull, permissionKeyString)); - } - - @Test(enabled = true) - public void test008MutiSignGodicWithdrawBanlanceTransaction() { - long MaintenanceTimeInterval = -1L; - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info("Index is:" + i); - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - if (getChainParameters.get().getChainParameter(i).getKey() - .equals("getMaintenanceTimeInterval")) { - MaintenanceTimeInterval = getChainParameters.get().getChainParameter(i).getValue(); - break; - } - } - - try { - Thread.sleep(MaintenanceTimeInterval); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Assert.assertTrue(PublicMethedForMutiSign.withdrawBalance(newAddress, newKey, - 2, permissionKeyString, blockingStubFull)); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java deleted file mode 100644 index 322cdf9e3be..00000000000 --- a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java +++ /dev/null @@ -1,399 +0,0 @@ -package stest.tron.wallet.witness; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestWitness001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = true) - public void testVoteWitness() { - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - HashMap wrongVoteMap = new HashMap(); - wrongVoteMap.put(voteStr, "-1"); - HashMap zeroVoteMap = new HashMap(); - zeroVoteMap.put(voteStr, "0"); - - HashMap veryLargeMap = new HashMap(); - veryLargeMap.put(voteStr, "1000000000"); - HashMap wrongDropMap = new HashMap(); - wrongDropMap.put(voteStr, "10000000000000000"); - - //Vote failed due to no freeze balance. - //Assert.assertFalse(VoteWitness(smallVoteMap, NO_FROZEN_ADDRESS, no_frozen_balance_testKey)); - - //Freeze balance to get vote ability. - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(fromAddress, 1200000L, 3L, - 2,null,testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Vote failed when the vote is large than the freeze balance. - Assert.assertFalse(voteWitness(veryLargeMap, fromAddress, testKey002)); - //Vote failed due to 0 vote. - Assert.assertFalse(voteWitness(zeroVoteMap, fromAddress, testKey002)); - //Vote failed duo to -1 vote. - Assert.assertFalse(voteWitness(wrongVoteMap, fromAddress, testKey002)); - //Vote is so large, vote failed. - Assert.assertFalse(voteWitness(wrongDropMap, fromAddress, testKey002)); - - //Vote success - Assert.assertTrue(voteWitness(smallVoteMap, fromAddress, testKey002)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java deleted file mode 100644 index 876f7b64b58..00000000000 --- a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java +++ /dev/null @@ -1,210 +0,0 @@ -package stest.tron.wallet.witness; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.WitnessComparator; - -//import stest.tron.wallet.common.client.WitnessComparator; - -@Slf4j -public class WalletTestWitness002 { - - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testQueryAllWitness() { - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - if (result.isPresent()) { - GrpcAPI.WitnessList witnessList = result.get(); - List list = witnessList.getWitnessesList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new WitnessComparator()); - GrpcAPI.WitnessList.Builder builder = GrpcAPI.WitnessList.newBuilder(); - newList.forEach(witness -> builder.addWitnesses(witness)); - result = Optional.of(builder.build()); - } - logger.info(Integer.toString(result.get().getWitnessesCount())); - Assert.assertTrue(result.get().getWitnessesCount() > 0); - for (int j = 0; j < result.get().getWitnessesCount(); j++) { - Assert.assertFalse(result.get().getWitnesses(j).getAddress().isEmpty()); - Assert.assertFalse(result.get().getWitnesses(j).getUrl().isEmpty()); - //Assert.assertTrue(result.get().getWitnesses(j).getLatestSlotNum() > 0); - result.get().getWitnesses(j).getUrlBytes(); - result.get().getWitnesses(j).getLatestBlockNum(); - result.get().getWitnesses(j).getLatestSlotNum(); - result.get().getWitnesses(j).getTotalMissed(); - result.get().getWitnesses(j).getTotalProduced(); - } - - //Improve coverage. - witnesslist.equals(result.get()); - witnesslist.hashCode(); - witnesslist.getSerializedSize(); - witnesslist.equals(null); - } - - @Test(enabled = true) - public void testSolidityQueryAllWitness() { - GrpcAPI.WitnessList solidityWitnessList = blockingStubSolidity - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(solidityWitnessList); - if (result.isPresent()) { - GrpcAPI.WitnessList witnessList = result.get(); - List list = witnessList.getWitnessesList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new WitnessComparator()); - GrpcAPI.WitnessList.Builder builder = GrpcAPI.WitnessList.newBuilder(); - newList.forEach(witness -> builder.addWitnesses(witness)); - result = Optional.of(builder.build()); - } - logger.info(Integer.toString(result.get().getWitnessesCount())); - Assert.assertTrue(result.get().getWitnessesCount() > 0); - for (int j = 0; j < result.get().getWitnessesCount(); j++) { - Assert.assertFalse(result.get().getWitnesses(j).getAddress().isEmpty()); - Assert.assertFalse(result.get().getWitnesses(j).getUrl().isEmpty()); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - class WitnessComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long - .compare(((Protocol.Witness) o2).getVoteCount(), ((Protocol.Witness) o1).getVoteCount()); - } - } -} - - diff --git a/framework/src/test/resources/config-test-mainnet.conf b/framework/src/test/resources/config-test-mainnet.conf index 5bcc27b398d..43a01a0feb9 100644 --- a/framework/src/test/resources/config-test-mainnet.conf +++ b/framework/src/test/resources/config-test-mainnet.conf @@ -211,7 +211,7 @@ genesis.block = { } localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { diff --git a/framework/src/test/resources/config-test-storagetest.conf b/framework/src/test/resources/config-test-storagetest.conf index 87e3eabea2d..5098e39b650 100644 --- a/framework/src/test/resources/config-test-storagetest.conf +++ b/framework/src/test/resources/config-test-storagetest.conf @@ -268,7 +268,7 @@ genesis.block = { //localWitnessAccountAddress = localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { @@ -285,4 +285,4 @@ vm = { } committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 -} \ No newline at end of file +} diff --git a/framework/src/test/resources/config-test.conf b/framework/src/test/resources/config-test.conf index 2cd108bf966..d506521965f 100644 --- a/framework/src/test/resources/config-test.conf +++ b/framework/src/test/resources/config-test.conf @@ -105,6 +105,64 @@ node { solidityPort = 8091 } + # use your ipv6 address for node discovery and tcp connection, default false + enableIpv6 = false + + # if your node's highest block num is below than all your pees', try to acquire new connection, default false + effectiveCheckEnable = false + + dns { + # dns urls to get nodes, url format tree://{pubkey}@{domain}, default empty + treeUrls = [ + #"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes1.example.org", + ] + + # enable or disable dns publish, default false + publish = false + + # dns domain to publish nodes, required if publish is true + dnsDomain = "nodes1.example.org" + + # dns private key used to publish, required if publish is true, hex string of length 64 + dnsPrivate = "b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291" + + # known dns urls to publish if publish is true, url format tree://{pubkey}@{domain}, default empty + knownUrls = [ + #"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes2.example.org", + ] + + staticNodes = [ + # static nodes to published on dns + # Sample entries: + # "ip:port", + # "ip:port" + ] + + # merge several nodes into a leaf of tree, should be 1~5 + maxMergeSize = 5 + + # only nodes change percent is bigger then the threshold, we update data on dns + changeThreshold = 0.1 + + # dns server to publish, required if publish is true, only aws or aliyun is support + serverType = "aws" + + # access key id of aws or aliyun api, required if publish is true, string + accessKeyId = "your-key-id" + + # access key secret of aws or aliyun api, required if publish is true, string + accessKeySecret = "your-key-secret" + + # if publish is true and serverType is aliyun, it's endpoint of aws dns server, string + aliyunDnsEndpoint = "alidns.aliyuncs.com" + + # if publish is true and serverType is aws, it's region of aws api, such as "eu-south-1", string + awsRegion = "us-east-1" + + # if publish is true and server-type is aws, it's host zone id of aws's domain, string + awsHostZoneId = "your-host-zone-id" + } + rpc { port = 50051 @@ -269,7 +327,7 @@ genesis.block = { //localWitnessAccountAddress = localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { @@ -286,4 +344,17 @@ vm = { } committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 -} \ No newline at end of file +} + +rate.limiter.global.qps = 1000 +rate.limiter.global.ip.qps = 1000 +rate.limiter.http = [ + { + component = "GetNowBlockServlet", + strategy = "GlobalPreemptibleAdapter", + paramString = "permit=1" + } +] + +node.dynamicConfig.enable = true +node.dynamicConfig.checkInterval = 0 \ No newline at end of file diff --git a/plugins/build.gradle b/plugins/build.gradle index 22e37737731..457fb739058 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -26,7 +26,7 @@ configurations.getByName('checkstyleConfig') { dependencies { //local libraries compile fileTree(dir: 'libs', include: '*.jar') - testCompile group: 'junit', name: 'junit', version: '4.12' + testCompile group: 'junit', name: 'junit', version: '4.13.2' testCompile group: 'org.mockito', name: 'mockito-core', version: '2.13.0' testCompile group: 'org.hamcrest', name: 'hamcrest-junit', version: '1.0.0.1' testCompile group: 'org.testng', name: 'testng', version: '6.14.3' diff --git a/protocol/src/main/protos/.travis.yml b/protocol/src/main/protos/.travis.yml deleted file mode 100644 index 34fa71b3d15..00000000000 --- a/protocol/src/main/protos/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: ruby - -cache: - directories: - - $HOME/protobuf - -sudo: false - -before_install: - - bash install-protobuf.sh - - bash install-googleapis.sh - -# check what has been installed by listing contents of protobuf folder -before_script: - - ls -R $HOME/protobuf - -# let's use protobuf -script: - - $HOME/protobuf/bin/protoc --java_out=./ ./core/*.proto ./api/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=./ ./core/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=./ ./api/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:./ ./api/*.proto - - - ls -l \ No newline at end of file diff --git a/protocol/src/main/protos/README.md b/protocol/src/main/protos/README.md index 6a28119119a..0eaf7b30a80 100644 --- a/protocol/src/main/protos/README.md +++ b/protocol/src/main/protos/README.md @@ -6,6 +6,3 @@ java-tron, wallet-cli and grpc-gateway git subtree pull --prefix src/main/protos/ protocol master - -## Run the included *.sh files to initialize the dependencies - diff --git a/protocol/src/main/protos/api/api.proto b/protocol/src/main/protos/api/api.proto index 70297d0959b..d23d6e01729 100644 --- a/protocol/src/main/protos/api/api.proto +++ b/protocol/src/main/protos/api/api.proto @@ -281,6 +281,9 @@ service Wallet { rpc UnDelegateResource (UnDelegateResourceContract) returns (TransactionExtention) { } + rpc CancelAllUnfreezeV2 (CancelAllUnfreezeV2Contract) returns (TransactionExtention) { + } + //Please use UpdateAsset2 instead of this function. rpc UpdateAsset (UpdateAssetContract) returns (Transaction) { option (google.api.http) = { diff --git a/protocol/src/main/protos/core/Discover.proto b/protocol/src/main/protos/core/Discover.proto index 4cc0d83b02a..fadb819e92d 100644 --- a/protocol/src/main/protos/core/Discover.proto +++ b/protocol/src/main/protos/core/Discover.proto @@ -11,6 +11,7 @@ message Endpoint { bytes address = 1; int32 port = 2; bytes nodeId = 3; + bytes addressIpv6 = 4; } message PingMessage { diff --git a/protocol/src/main/protos/core/Tron.proto b/protocol/src/main/protos/core/Tron.proto index dafee3a6afd..aa6a96ba1b3 100644 --- a/protocol/src/main/protos/core/Tron.proto +++ b/protocol/src/main/protos/core/Tron.proto @@ -193,6 +193,7 @@ message Account { bytes account_id = 23; int64 net_window_size = 24; + bool net_window_optimized = 25; message AccountResource { // energy resource, get from frozen @@ -215,6 +216,7 @@ message Account { int64 delegated_frozenV2_balance_for_energy = 10; int64 acquired_delegated_frozenV2_balance_for_energy = 11; + bool energy_window_optimized = 12; } AccountResource account_resource = 26; bytes codeHash = 30; @@ -374,6 +376,7 @@ message Transaction { WithdrawExpireUnfreezeContract = 56; DelegateResourceContract = 57; UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; @@ -422,6 +425,7 @@ message Transaction { bytes orderId = 25; repeated MarketOrderDetail orderDetails = 26; int64 withdraw_expire_amount = 27; + map cancel_unfreezeV2_amount = 28; } message raw { @@ -482,6 +486,7 @@ message TransactionInfo { int64 packingFee = 27; int64 withdraw_expire_amount = 28; + map cancel_unfreezeV2_amount = 29; } message TransactionRet { @@ -595,6 +600,7 @@ enum ReasonCode { CONNECT_FAIL = 0x21; TOO_MANY_PEERS_WITH_SAME_IP = 0x22; LIGHT_NODE_SYNC_FAIL = 0x23; + BELOW_THAN_ME = 0X24; UNKNOWN = 0xFF; } diff --git a/protocol/src/main/protos/core/contract/balance_contract.proto b/protocol/src/main/protos/core/contract/balance_contract.proto index 90a2dfaa48d..ea1c96270d6 100644 --- a/protocol/src/main/protos/core/contract/balance_contract.proto +++ b/protocol/src/main/protos/core/contract/balance_contract.proto @@ -103,6 +103,7 @@ message DelegateResourceContract { int64 balance = 3; bytes receiver_address = 4; bool lock = 5; + int64 lock_period = 6; } message UnDelegateResourceContract { @@ -110,4 +111,8 @@ message UnDelegateResourceContract { ResourceCode resource = 2; int64 balance = 3; bytes receiver_address = 4; +} + +message CancelAllUnfreezeV2Contract { + bytes owner_address = 1; } \ No newline at end of file diff --git a/protocol/src/main/protos/install-googleapis.sh b/protocol/src/main/protos/install-googleapis.sh deleted file mode 100755 index e1c1df80124..00000000000 --- a/protocol/src/main/protos/install-googleapis.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -set -e - -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -go get -u github.com/golang/protobuf/protoc-gen-go - -wget https://repo1.maven.org/maven2/com/google/api/grpc/googleapis-common-protos/0.0.3/googleapis-common-protos-0.0.3.jar -jar xvf googleapis-common-protos-0.0.3.jar -cp -r google/ $HOME/protobuf/include/ -ls -l - - - diff --git a/protocol/src/main/protos/install-protobuf.sh b/protocol/src/main/protos/install-protobuf.sh deleted file mode 100755 index b3a8cb5cbb2..00000000000 --- a/protocol/src/main/protos/install-protobuf.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -set -e -# check to see if protobuf folder is empty -if [ ! -d "$HOME/protobuf/lib" ]; then - wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.tar.gz - tar -xzvf protobuf-all-3.5.1.tar.gz - cd protobuf-3.5.1 && ./configure --prefix=$HOME/protobuf && make && make install -else - echo "Using cached directory." -fi diff --git a/checkStyle.sh b/script/checkStyle.sh similarity index 100% rename from checkStyle.sh rename to script/checkStyle.sh diff --git a/codecov.sh b/script/codecov.sh similarity index 100% rename from codecov.sh rename to script/codecov.sh diff --git a/querySonar.sh b/script/querySonar.sh similarity index 100% rename from querySonar.sh rename to script/querySonar.sh diff --git a/sonar.sh b/script/sonar.sh similarity index 100% rename from sonar.sh rename to script/sonar.sh diff --git a/work.sh b/work.sh deleted file mode 100755 index 91d7247ca57..00000000000 --- a/work.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash - -# Function: to start, stop and restart java-tron. -# Usage: bash work.sh start|stop|restart. -# Note: modify the paths and private key to your own. - -# Auther: haoyouqiang -# Since: 2018/5/27 -# Version: 1.0 - -if [ $# -ne 1 ]; then - echo "Usage: bash work.sh start|stop|restart." - exit 1 -fi - -# Increase memory limit that JVM can use to avoid OOM error: -# 80% of your physical memory may be a proper ceiling that JVM can use. -# By default there, JVM initializes with 1g memory and can use 32g at most. -JVM_OPTIONS="-Xms1g -Xmx32g" - -JAR_FILE_PATH="./build/libs/java-tron.jar" -PID_FILE_PATH="java-tron.pid" -LOG_FILE_PATH="java-tron.log" - -CONF_FILE_PATH="./build/resources/main/config.conf" - -PRIVATE_KEY="650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812" - -case "${1}" in - start) - # Already running - if [ -f ${PID_FILE_PATH} ]; then - pid=$(cat ${PID_FILE_PATH}) - if $(ps -p ${pid} > /dev/null); then - echo "Already running [PID: ${pid}], you can stop it and retry." - exit 1 - fi - fi - - nohup java ${JVM_OPTIONS} \ - -jar ${JAR_FILE_PATH} \ - -p ${PRIVATE_KEY} --witness \ - -c ${CONF_FILE_PATH} \ - > ${LOG_FILE_PATH} 2>&1 \ - & echo $! > ${PID_FILE_PATH} - - if [ $? -eq 0 ]; then - echo "Succeeded to start java-tron." - else - echo "Failed to start java-tron." - fi - ;; - stop) - kill $(cat ${PID_FILE_PATH}) - - if [ $? -eq 0 ]; then - rm ${PID_FILE_PATH} - echo "Succeeded to stop java-tron." - else - echo "Failed to stop java-tron." - fi - ;; - restart) - ${0} stop && sleep 1 && ${0} start - ;; -esac -